关键点在于图片从后端回传的时候图片对象的格式如果缺少 type = 'image', url='XXXXX', van-uploader控件不能正确回显。
// component/upLoadFile/upLoadFile.js
import API from '../../api/api'
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
Component({
properties:{
cellTitle: String,
allReadyTitle: String,
upLoadShow: Boolean,
fileList: Array
},
/**
* 页面的初始数据
*/
data: {
fileList: [],
returnList: [],
newImgArr: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
methods:{
afterRead(event) {
const that = this;
return new Promise((ress,rej) => {
const { file } = event.detail;
this.setData({
fileList: that.data.fileList.concat(file)
})
file.map((file) => {
wx.uploadFile({
url: API.uploadOneFile,
filePath: file.url,
name: 'file',
header: {},
formData: {
},
success(res) {
let result = JSON.parse(res.data)
var arr = that.data.returnList
arr.push(result.data)
that.setData({
returnList: arr
})
ress()
},
fail(res) {
Toast(result.message)
}
});
})
}).then(() => {
that.triggerEvent('ReturnList', that.data.returnList)
})
},
deleteImg(e) {
let index= e.detail.index
this.data.fileList.splice(index,1)
this.data.returnList.splice(index,1)
let newArr = this.data.fileList
let newArr2 = this.data.returnList
this.setData({
fileList: newArr,
returnList: newArr2
})
},
previewPic(e) {
const that = this
let result = JSON.parse(e)
that.setData({
returnList: that.data.returnList.concat(result)
})
result.map(e => {
let arr = this.data.fileList
arr.push(e)
this.setData({
fileList: arr
})
})
this.imgListChuLi()
},
imgListChuLi() {
let arr = this.data.fileList
let newArr = this.data.newImgArr
for (let i = 0; i < arr.length; i++) {
let index = arr[i].value.indexOf(".");
let con = arr[i].value.substring(index + 1, arr[i].value.length)
arr[i].type = con
arr[i].isImage = true
arr[i].url = app.globalData.apiHost + '/CLRentDp/api/file/downloadFile?filePath=' + encodeURI(arr[i].value)
newArr.push(arr[i].url)
}
this.setData({
fileList: arr,
newImgArr: newArr
})
},
preview(e) {
let tag = e.currentTarget.dataset.type
let src = e.currentTarget.dataset.src
if (tag == 'jpg' || tag == 'jpeg' || tag == 'png' || tag == 'gif') {
wx.previewImage({
current: src, // 当前显示图片的http链接
urls: this.data.newImgArr // 需要预览的图片http链接列表
})
}
else {
wx.downloadFile({
url: src,
success: function (res) {
console.log(res)
const filePath = res.tempFilePath
wx.openDocument({
fileType: tag,
filePath: filePath,
success: function (res) {
console.log('打开文档成功')
},
fail() {
Toast('非法文件类型!')
}
})
}
})
}
}
}
})