本文详细介绍微信小程序中实现多张照片上传与展示的具体方法。通过封装mp-uploader组件或使用wx.chooseImage API,结合for循环依次将图片路径上传至服务器。服务器返回状态码200后,将图片src转换为JSON字符串存入数据库。前端获取数据时,将字符串解析为数组对象即可实现图片列表的循环展示,完整代码与关键逻辑均包含在内。
微信小程序实现多张照片上传
1.功能实现
当用户选择图片后,系统会生成包含文件路径的tempFilePaths对象。随后通过for循环依次将每张图片的src上传至服务器。当服务器返回状态码为200且所有图片上传完毕后,将图片的src转换为JSON字符串,并存储在数组中,以便后续添加到数据库中。
2.代码实现
1.mp-uploader
<view class="page">
<view class="page__bd">
<mp-cells>
<mp-cell>
<mp-uploader select="{{selectFile}}" upload="{{uplaodFile}}" files="{{files}}" max-count="4" title="附件上传" tips="最多可上传4张照片"></mp-uploader>
</mp-cell>
</mp-cells>
</view>
</view>//data中
this.setData({
selectFile: this.selectFile.bind(this),
uplaodFile: this.uplaodFile.bind(this)
}) uplaodFile(files) {
console.log('upload files', files)
console.log('upload files', files)
// 文件上传的函数,返回一个promise
return new Promise((resolve, reject) => {
const tempFilePaths = files.tempFilePaths;
//上传返回值
const that = this;
const object = {};
for (var i = 0; i < tempFilePaths.length; i++) {
let filePath = tempFilePaths[i]
wx.uploadFile({
filePath: filePath,
name: 'file',
url: 'http://localhost:3000/upload/upload',
success: function(res){
console.log('444',res.statusCode)
if (res.statusCode=== 200 ) {
const url = JSON.parse(res.data).url
that.data.files.push(url)
if (that.data.files.length === tempFilePaths.length) {
object.urls = that.data.files;
resolve(object) //这就是判断是不是最后一张已经上传了,用来返回,
}
} else {
reject('error')
}
}
})
}
})
// 文件上传的函数,返回一个promise
},

2.chooseImage
<view>
<block wx:for="{{images}}" wx:for-item="src">
<image src="{{src}}"></image>
</block>
<view bindtap="upload">上传</view>upload(){
let that = this;
wx.chooseImage({//异步方法
count: 9,//最多选择图片数量
sizeType: ['original', 'compressed'],//选择的图片尺寸 原图,压缩图
sourceType: ['album', 'camera'],//相册选图,相机拍照
success(res) {
//tempFilePaths可以作为图片标签src属性
const tempFilePaths = res.tempFilePaths
console.log("选择成功", res)
for (let i = 0; i < tempFilePaths.length; i++) {//多个图片的循环上传
wx.cloud.uploadFile({//上传至微信云存储
cloudPath: 'myImage/' + new Date().getTime() + "_" + Math.floor(Math.random() * 1000) + ".jpg",//使用时间戳加随机数作为上传至云端的图片名称
filePath: tempFilePaths[i],// 本地文件路径
success: res => {
// 返回文件 ID
console.log("上传成功", res.fileID)
that.setData({
images: res.fileID//获取上传云端的图片在页面上显示
})
wx.showToast({
title: '上传成功',
})
}
})
}
}
})
}3.页面展示
图片的src在数据库中是以字符串的形式存储。当需要展示时,我们只需要将字符串转化为数组对象即可。例如原始数据为:“http://localhost:3000/images/17112466754606371.jpg”,“http://localhost:3000/images/17112466755133666.jpg”,“http://localhost:3000/images/17112466756494564.jpg”
getShare().then(res=>{
const list=res.data
list.forEach(obj => {
console.log('8888',obj.img)
const imgString = obj.img;
const trimmedString = imgString.replace('["', '').replace('\"]', '');
const imgArray = trimmedString.split('"\,\"');
console.log('444',imgArray)
obj.img = imgArray;
})
this.setData({
shareList:list
})
})
🎉写在最后
🍻伙伴们,如果你已经看到了这里,觉得这篇文章有帮助到你的话不妨点赞👍或 Star ✨支持一下哦!手动码字,如有错误,欢迎在评论区指正💬~
到此这篇关于微信小程序实现多张照片上传的文章就介绍到这了,更多相关小程序多张照片上传内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!