前言:在uniapp官方文檔中的uni-file-picker組件可實(shí)現(xiàn)圖片上傳功能,官方文檔:uniapp官網(wǎng) 中的案例不能完全滿足需求,官網(wǎng)中默認(rèn)的是上傳到自帶的服務(wù)空間
以下是代碼:
view代碼:
:auto-upload="false"加上這個(gè)取消自動(dòng)上傳
<uni-file-picker v-model="filePathsList" :auto-upload="false" file-mediatype="image" mode="grid"
fileMediatype="image" @select="handleSelect" @delete="handleDelete" />
methods方法
選擇圖片
async handleSelect(res) {
await this.uploadImg(res.tempFilePaths, 1);
},
上傳圖片
async uploadImg(tempFilePaths, token) {
if (!tempFilePaths.length) return; //如果沒有選擇圖片就退出
//循環(huán)選擇圖片的張數(shù)
tempFilePaths.map(async () => {
const path = tempFilePaths.pop();
//因?yàn)槲疫@個(gè)后臺(tái)給的接口一次只能上傳一張圖片,所以每循環(huán)一次就調(diào)用接口上傳一次
const [err, {data}] = await uni.uploadFile({
url: 'https://localhost/file/api/uploadtemp',//后臺(tái)地址
filePath: path,
name: 'file',
formData: {
'user': 'test'
},
});
//因?yàn)閍sync返回的是個(gè)promise對(duì)象,所以要把返回的數(shù)據(jù)轉(zhuǎn)為對(duì)象格式。
let dataObj = JSON.parse(data)
//每循環(huán)一次就把后臺(tái)返回的圖片地址添加到filePathsList數(shù)組
this.filePathsList.push({
url: dataObj.data,
name: ""
})
})
console.log('filePathsList', this.filePathsList);
this.uploadImg(tempFilePaths, token);
},
刪除圖片
handleDelete(err) { // 刪除圖片
const num = this.filePathsList.findIndex(v => v.url === err.tempFilePath);
this.filePathsList.splice(num, 1);
},
上傳事例:
參考http://t.csdn.cn/RWQ85這個(gè)博主寫的,自己修改了一點(diǎn)。
疑問(wèn) 參考博主的文章中這個(gè)代碼 this.isGuid 不知道是什么意思,希望有人看到了可以講解下。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-514072.html
if (!this.isGuid(data)) {
// upload fail
this.filePathsList.pop()
uni.showToast({
title: "上傳失敗",
icon: "none"
})
}else{
// upload success
this.filePathsList[this.filePathsList.length - 1].name = data
}
(自己的筆記)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-514072.html
到了這里,關(guān)于uniapp中的uni-file-picker組件上傳多張圖片到服務(wù)器,可添加,預(yù)覽,刪除圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!