Uniapp 图片前端上传功能实现与详解
实现UniApp前端图片上传功能
UniApp作为跨平台开发框架,提供了便捷的API实现图片上传功能。以下是一个完整的实现方案,包含错误处理和用户体验优化。
核心代码结构分析
uploadpic: function() {let that = thisuni.chooseImage({count: 1,sizeType: ["original", "compressed"],sourceType: ["camera", "album"],success: async (res) => {uni.showLoading({title: "上传中...",mask: true,});try {const tempFilePath = res.tempFilePaths[0]let tempFiles = res.tempFiles[0]const timestamp = new Date().getTime()const videoName = `${timestamp}_${tempFiles.name}`const { success, data, message } = await ossUpload(tempFilePath,videoName,"");if (success && data) {that.refund_reason_wap_imgPath.push(data)} else {uni.showToast({title: message || "上传失败",icon: "none",mask: true,});}} catch (error) {console.error("上传过程出错:", error)uni.showToast({title: "上传过程发生错误",icon: "none",mask: true,})} finally {uni.hideLoading()}},fail: (err) => {if (err.errMsg !== "chooseImage:fail cancel") {uni.showToast({title: "选择图片失败,请重试",icon: "none",mask: true,})}}})
}
关键功能实现细节
图片选择配置
count:1
限制单次选择一张图片sizeType
支持原图和压缩图两种格式sourceType
同时启用相机和相册两种来源
上传流程优化
- 添加时间戳前缀确保文件名唯一性
- 显示加载提示防止重复操作
- 使用try-catch-finally结构确保异常捕获和提示关闭
错误处理机制
用户取消操作处理
通过判断err.errMsg !== "chooseImage:fail cancel"
避免对用户取消操作显示错误提示
上传失败处理
- 显示具体的错误信息(message)或默认提示
- 保持遮罩层防止误操作
- 最终都会执行
uni.hideLoading()
实际应用建议
性能优化方向
- 对大图进行压缩处理
- 实现多图上传队列
- 添加进度条显示
扩展功能
- 增加图片预览功能
- 实现图片裁剪编辑
- 添加上传重试机制
通过这套实现方案,开发者可以快速构建稳定可靠的图片上传功能,同时保持良好的用户体验。代码结构清晰,错误处理完善,适合直接集成到各类UniApp项目中。