微信小程序,uniapp 多图片上传

小程序多图片上传
方法一,多图上传

2020年11月30日 补充
之前看到了新的多图上传方法 今天有时间整理了下,新方法支持 async... await... 可以使用 then 进行接收完成值

$uploadFile(img = [], i = 0) {
	return this.$services.globalOSSUpload(img[i]).then(res => {
		i++
		if(i >= img.length || i >= 9) return [].concat(res.data)
		return this.$uploadFile(img, i).then(e => [].concat(res.data, e))
	}, err => {
		// 图片上传失败的处理,比如重新上传
	})
},

globalOSSUpload 图片上传接口

globalOSSUpload(filePath, config){
	return Request.postFile(api.globalOSSUpload, filePath, config, false)
},

postFile 文件上传函数

postFile(...params){
	return UpLoadFile(...params).then(res => Promise.resolve(res))
}
export const UpLoadFile = function(url, filePath, config = {}, loading = false){
	url = API_URL + url
	let {isLogin, userInfo} = Store.state
	let header = {
		'token': isLogin ? userInfo.token : ''
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url,
			filePath,
			name: 'file',
			header,
			...config,
			success(res){
				let data = JSON.parse(res.data)
				// 相应的条件处理
				reject(data)
			},
			fail(err){
				reject(err)
			},
			complete(res) {
				// 相应的条件处理
				switch(res.statusCode){
					case 404:
						workerError('网络错误', '信息走丢咯(ಥ_ಥ),可能是网络问题,请稍后再试!')
						break
					case 500:
						workerError('服务器异常', '服务器开小差了(ಥ_ಥ),程序员正在努力抢修中...请稍后再试!')
						break
				}
			}
		})
	})
}
方法二

文件上传 微信小程序官方文档

这里为了方便使用,对 小程序文件上传的函数进行了 再次的封装;同时为了方便记忆,是和使用,按照微信给出的文档进行编写;
先看一下怎么使用吧!

// 选择照片
wx.chooseImage({
  success: function(res) {
    console.log(res, app.util.url('applet_img_upload'));
    // 这里把地址 和 上传照片,都放在了一个 util.js 中
    // 在 app.js 中 util: requier('utils/util.js')
    app.util.uploadFile({
      url: app.util.url('applet_img_upload'),
      filePath: res.tempFilePaths,	// 也可以传单张 res.tempFilePaths[0],这样好像 多此一举了
      name: 'image',			// 具有默认值,可写可不写
      success: e => {
        console.log(e);
      },
      fail: err => {
        console.log(err);
      }
    })
  },
})

这里把该函数放到了 util.js 中;放到其他地方也是可以的;

/*
 * @param {Object}
 * upImageFile({url: 'test.com', filePath: ['1.png', '2.png'], name: 'image', success: res => {}, fail: err => {} })
 */
 // i 记录当前上传的图片 fileUrl 图片上传后的地址 err 记录上传失败,或错误次数
 uploadFile: function (obj, i = 0, fileUrl = [], err = 0) {
 	// 有时也可能会直接上传单张图片
   if (typeof obj.filePath === 'string') obj.filePath = [obj.filePath];
   wx.uploadFile({
     url: obj.url,					// 接收图片的地址
     filePath: obj.filePath[i],		// 图片的临时路径,由微信返回
     name: obj.name || "image",		// 对应的 key,这里设置默认 image
     success: res => {
       var resData = res.data;
       // 异常处理,有时后台返回的数据可能会有点问题,这个看需求写
       try {
         resData = JSON.parse(resData);
       }
       catch (err) {
         resData = JSON.parse(resData.substring(1));
       }
       if (resData.ec === 200) {                       // 判断上传是否成功,根据后台返回的状态判定,这里需要根据你自己后台返回的状态去判断
         i++;
         fileUrl.push(resData.data.path);              // 后台返回图片路径
         // 如果都上传完毕 直接 执行 success
         if (i === obj.filePath.length) {
           if (obj.success) obj.success({ msg: 'uploadFile:ok', data: fileUrl, statusCode: res.statusCode });
         }
         // 如果没有完成 则继续调用该函数
         else {
           this.uploadFile(obj, i, fileUrl);
         }
       }
       else {
       	// 如果没有失败,记录上传失败次数,我这里定义上传 失败 3次结束执行上传,返回失败结果,执行 fail;后续如果有需求,这块你也可以改成动态的
         err++;
         if (err <= 3) this.uploadFile(obj, i, fileUrl, err);
         else {
           console.log('%c 返回信息:', 'color: #f00', resData)
           console.log('%c 请注意: 请求成功时,后台返回的信息可能与此函数中的配置不一致,注意修改', 'color: blue');
         }
       }
     },
     fail: err => {
     // 上传失败执行,同上
       err++;
       if (err <= 3) this.uploadFile(obj, i, fileUrl, err);
       else {
         var errObj = { err, i, fileUrl };
         if (obj.fail) obj.fail(errObj);
         console.log('%c 图片上传失败,请注意检查...', 'color: #f00', errObj);
       }
     }
   })
 }

T.T

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Uniapp 中实现微信小程序的多张图片上传,可以按照以下步骤进行操作: 1. 在页面中创建一个按钮,用于触发选择图片的操作。 2. 在按钮的点击事件中,调用 `uni.chooseImage` 方法来选择图片。这个方法会返回选择的图片的临时文件路径。 3. 将选择的图片路径保存在一个数组中。 4. 在页面中展示已选择的图片,可以使用 `v-for` 指令来遍历已选择的图片数组,使用 `uni.previewImage` 方法来预览图片。 5. 创建一个提交按钮,在点击事件中调用 `uni.uploadFile` 方法,将选择的图片上传到服务器。 下面是一个示例代码: ```html <template> <view> <button @tap="chooseImage">选择图片</button> <view v-for="(image, index) in imageList" :key="index"> <image :src="image" mode="aspectFit" @tap="previewImage(index)" /> </view> <button @tap="uploadImages">上传图片</button> </view> </template> <script> export default { data() { return { imageList: [], // 存放已选择的图片路径 }; }, methods: { chooseImage() { uni.chooseImage({ count: 9, // 最多可以选择的图片张数 success: (res) => { // 将选择的图片路径保存到 imageList 数组中 this.imageList = res.tempFilePaths; }, }); }, previewImage(index) { uni.previewImage({ urls: this.imageList, // 需要预览的图片路径列表 current: this.imageList[index], // 当前显示的图片链接 }); }, uploadImages() { // 遍历已选择的图片路径,逐个上传 this.imageList.forEach((image) => { uni.uploadFile({ url: 'https://your-upload-api-url', // 上传图片的接口地址 filePath: image, name: 'file', // 上传文件对应的 key 值 formData: {}, // 其他额外的参数 success: (res) => { console.log(res.data); }, }); }); }, }, }; </script> ``` 请注意替换示例代码中的上传接口地址为你自己的接口地址。另外,需要在 `manifest.json` 文件中添加相应的权限配置,以允许选择图片和上传文件。 希望这个示例对你有帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值