uniapp 实现多个图片上传(需用 uniCould)
前言
在用uniapp 编写程序时,遇到上传图片问题,可以使用 uniCould 的API uploadFile() 但是该接口一次只能上传一张图片,当需要上传多张照片时,就需要在其基础上进行改动,本文就是用自己的理解实现多张图片上传问题
提示:以下是本篇文章正文内容,下面案例可供参考
一、uploadFile() 是什么?
uploadFile(Object object)
直接上传文件到云存储。
客户端上传文件到云函数、云函数再上传文件到云存储,这样的过程会导致文件流量带宽耗费较大。所以一般上传文件都是客户端直传。
官方文档 [https://uniapp.dcloud.io/uniCloud/storage?id=gettempfileurl]
二、使用步骤
<button type="default" @click="chooseImages" >上传</button>
<button type="default" @click="getImages" >下载链接</button>
1.上传图片
chooseImages(){
// 上传图片
uni.chooseImage({
count: 9,
success: (res) => {
// console.log(res);
// 获取每个图片的本地上传地址
this.getPic(res.tempFilePaths);
},
2.获取每个图片的上传地址
async getPic(picUrl) {
// 用循环遍历每一个上传图片的本地地址
for (var i = 0; i < picUrl.length; i++) {
// console.log(picUrl[i]);
// 将本地地址传入服务器,实现图片上传
await uniCloud.uploadFile({
filePath: picUrl[i],
// 上传图片名字可自己定义
cloudPath: i + '.jpg',
onUploadProgress:function(progressEvent){
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
}
}).then(res => {
// console.log(res)
// imagesUrl 在 data 里定义的接收 图片地址 的数组
this.imagesUrl.push(res.fileID) ;
})
}
// 上传后的服务器图片地址
console.log(this.imagesUrl);
},
3.获取每个图片的可下载地址
getImages(imagesUrl) {
uniCloud.getTempFileURL({
fileList: this.imagesUrl,
}).then(res => {
// res.fileList 图片相关信息的数组
console.log(res.fileList);
})
}
总结
以上就是今天要讲的内容,本文仅仅是自己的一点拙见,欢迎大家评论,希望能够帮助到和我一样的前端小白。