需求:小程序端上傳圖片,可一次傳多張照片、預覽、刪除。
問題:vant寫的對我這種沒有基礎的人來說,確實有點頭疼,參考了這篇參考鏈接,然后根據(jù)需求改了改。
實現(xiàn)結(jié)果:
代碼:
wxml:
<!-- 傳圖片 -->
<view class="addImage" >
<van-uploader
file-list="{{ fileList }}"
accept="image"
max-count="9"
multiple
bind:after-read="afterRead"
bind:delete="deleteImg"
bind:before-read="beforeRead"
deletable="{{ true }}"
preview-size="{{(width+50)/4 }}" />
</view>
js:后端部分,請根據(jù)自己后端接口修改文章來源:http://www.zghlxwxcb.cn/news/detail-516885.html
//文件讀取完成后
afterRead(event) {
const { file } = event.detail;
var that = this
const fileList = that.data.fileList
//獲得這次上傳的圖片數(shù)量,上傳時避免重復上傳之前傳過的文件
const thisNum = file.length
const beforeNum = fileList.length
const totalNum = thisNum + beforeNum
//還沒上傳時將選擇的圖片的上傳狀態(tài)設置為加載
for (let j = 0; j < thisNum; j++) {
file[j].status='uploading'
fileList.push(file[j])
}
that.setData({ fileList })
// console.log('fileList',that.data.fileList)
// console.log('file',file)
//上傳服務器
for (let i = beforeNum; i < totalNum; i++) {
that.uploadImg(i,that.data.fileList[i].url )
}
},
js:文章來源地址http://www.zghlxwxcb.cn/news/detail-516885.html
uploadImg(fileListIndex,fileURL) {
var that = this
//上傳文件
const filePath = fileURL // 小程序臨時文件路徑
// console.log("filePath",filePath)
wx.uploadFile({
url: '后端地址',
filePath: filePath,
name: 'file',
header: {
"Content-Type": "multipart/form-data",
},
formData: {
fileType:'image',
reName:'true',
thumbnail:'true'
},
success(res) {
var tem = JSON.parse(res.data)
// 上傳完成需要更新 fileList
that.setData({
[`fileList[${fileListIndex}].url`]: tem.data.fileUrl,
[`fileList[${fileListIndex}].status`]: 'done'
})
wx.showToast({ title: '上傳成功', icon: 'none' })
},
fail: function (res) {
console.log("file upload fail")
},
})
},
到了這里,關于小程序上傳圖片+Vant(可一次傳多張圖片)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!