微信小程序上传多张图片

13

微信小程序上传多张图片

微信小程序上传多张图片

开发微信小程序时,时常会用到多图上传的情况。由于微信API的特性,一次只能上传一张图片,但是实际情况是我们通常会要求一次上传多张图片,所以只能通过循环调用 `wx.uploadFile` 来实现上传多张图片。

问题描述

在开发微信小程序时,我们经常需要让用户上传多张图片。例如,在一个照片墙应用中,用户可以选择多张照片并上传到服务器上。但是,由于微信API的限制,一次只能上传一张图片。这意味着我们需要通过循环调用 `wx.uploadFile` 来实现上传多张图片。

解决方案

为了解决这个问题,我们可以使用以下方法:

1. 获取用户选择的图片列表

首先,我们需要让用户选择多张照片。我们可以使用 `wx.chooseImage` 方法来获取用户选择的图片列表。

```javascriptconst imgList = await wx.chooseImage({

count:9, // 最多选择9张图片 sizeType: ['original'], // 只允许选择原图 sourceType: ['album'] // 从相册中选择})

```

2. 循环上传图片

接下来,我们需要通过循环调用 `wx.uploadFile` 来实现上传多张图片。我们可以使用 `for...of` 循环来实现。

```javascriptconst formData = new FormData();

for (let i =0; i < imgList.tempFilePaths.length; i++) {

const file = wx.getFileSystemManager().createFile({

filePath: imgList.tempFilePaths[i],

name: 'image'

});

formData.append('images', file);

}

```

3. 上传图片

最后,我们需要通过 `wx.uploadFile` 来实现上传图片。我们可以使用 `formData` 对象来传递文件。

```javascriptconst res = await wx.uploadFile({

url: ' filePath: formData,

name: 'images'

})

```

完整代码

以下是完整的代码:

```javascriptPage({

data: {},

chooseImage() {

const imgList = wx.chooseImage({

count:9, // 最多选择9张图片 sizeType: ['original'], // 只允许选择原图 sourceType: ['album'] // 从相册中选择 })

return imgList;

},

uploadImages(imgList) {

const formData = new FormData();

for (let i =0; i < imgList.tempFilePaths.length; i++) {

const file = wx.getFileSystemManager().createFile({

filePath: imgList.tempFilePaths[i],

name: 'image'

});

formData.append('images', file);

}

return formData;

},

uploadImage(formData) {

return wx.uploadFile({

url: ' filePath: formData,

name: 'images'

})

},

async handleUpload() {

const imgList = await this.chooseImage();

const formData = await this.uploadImages(imgList);

const res = await this.uploadImage(formData);

console.log(res);

}

})

```

注意

* `wx.chooseImage` 方法返回一个 Promise 对象,需要使用 `await` 关键字来等待其结果。

* `wx.getFileSystemManager().createFile` 方法创建一个文件对象,需要传递 `filePath` 和 `name` 参数。

* `wx.uploadFile` 方法上传文件到服务器上,需要传递 `url`、`filePath` 和 `name` 参数。

以上是关于微信小程序上传多张图片的详细描述。

小程序前端开发微信小程序

版权声明:除非特别标注,否则均为网络文章,侵权请联系站长删除。

上一篇 HBuilderX搭建微信小程序;HBuilderX开发uni-app微信小程序;uni-app开发微信小程序;使用uni-app搭建微信...

下一篇 微信小程序的动态修改视图层的数据 —— 微信小程序教程系列(3)