一、uni-file-picker 组件
通过uni-file-picker 组件得到要上传的文件fileList
<uni-file-picker
fileMediatype="image"
:value="fileLists"
@select="select"
/>
<script>
export default {
data() {
return {
//已选择的上传文件
fileList: [],
// 回显
fileLists:[{
url: 'https://qiniu-webassets.dcloud.net.cn/unidoc/zh/shuijiao-small.jpg',
extname: 'png',
name: 'shuijiao.png'
}]
}
},
methods:{
// 选择文件后触发
select(e){
console.log('选择文件:',e)
this.fileList.push(e.tempFiles[0])
}
}
}
</script>
二、uni.uploadFile api
说明:
1、files属性不支持小程序,即小程序中只能用filePath,每次只能上传一张图片,对于选择上传多个文件时,只能遍历上传 如下:
onClickUpload() {
if (this.fileList.length === 0) {
uni.showToast({
title: "至少上传一张图片!",
icon: "error",
duration: 2000
})
} else {
let file = []
// 遍历上传
this.fileList.forEach((el, i) => {
api.uploadFile(el).then(res => {
if (res.code === 200) {
file.push(res.data)
if (i === this.fileList.length - 1) {
this.saveStep(file)
this.fileList = []
}
}
})
})
}
},
2、uni.uploadFile的封装
uploadFile(url, file, config = {}) {
let token = uni.getStorageSync('publicToken')
const absoluteUrl = (config.baseURL || this.defaults.fileBaseURL) + url + "?access_token=" + token;
const mergedOptions = {
url: absoluteUrl,
filePath: file.url,
name: 'file',
formData: {
'bizId': 'tph'
},
...config,
};
return new Promise((resolve, reject) => {
uni.uploadFile({
...mergedOptions,
success: (res) => {
if (res.statusCode === 200) {
resolve(JSON.parse(res.data));
} else {
reject(res);
}
},
fail: res => reject(res),
complete: function() {
uni.hideLoading();
}
})
})
}
3、基于fasdfs的图片回显
let imgFile = JSON.parse(item.punchfiles)
imgFile.forEach(el => {
this.fileLists.push({
url: configUrl.baseURL + configUrl.downProductUrl + '?fileName=' + el.filePath +'&access_token=' + uni.getStorageSync('publicToken'),
extname: el.fileType,
name: el.fileSaveName
})
})
其中的url也可以如下:
this.imgUrl = this.getImgApi + data.filePath + '&bizId=' + this.bizId + '&access_token=' + this.accessToken
三、遇到的坑
uniapp不支持小程序多文件的一次性上传,只能通过遍历,多次请求上传api解决