一、前言
这里主要记录一下如何使用uni-app上传本地图片,以及上传多张图片到后端的处理方法
二、处理过程
上传本地图片的组件主要用的是 uview 的 u-upload 组件
上传到后端的方法是 uniapp 的 uni-uploadFile() API
多张图片上传完毕(即接口都返回成功后)再执行其他代码会用到 Promise.all()
// fileList指的是保存的图片列表,afterRead是图片选择后需要处理的事件,delete是删除图片事件
<u-upload :fileList="imageList" @afterRead="afterReadImage" @delete="deleteImage"></u-upload>
// 提交按钮
<u-button text="提交" @click="submitData"></u-button>
data() {
return {
imageList: [],
};
},
methods: {
// 选择图片
afterReadImage(event) {
this.imageList.push(event.file);
},
// 删除图片
deleteImage(event) {
this.imageList = this.imageList.filter((p, index) => index != event.index);
},
// 提交按钮
async submitData() {
// 重点:这里由于是多张图片,所有需要依次遍历所有图片并发送多次请求,同时将所有的请求信息都保存到Promise.all()中
const uploadPromiseArr = this.imageList.map((p) =>
// 使用uni.uploadFile API,url表示上传到后端的地址,name是上传文件的关键字,filePath是本地图片资源路径,formData中添加的是自定义备注信息,不需要也可以不填
uni.uploadFile({
url: "http://www.example.com/upload",
name: "file",
filePath: p.url,
formData: {
biz: "zyxj",
},
})
);
// 使用Promise.all来确保多张图片都上传完毕后在执行后面的代码
const response = await Promise.all(uploadPromiseArr);
...后面的其他代码
}
}