uniapp上傳單張/多張照片到服務(wù)器(封裝方法)
//operate.js文件內(nèi)容
//export const api = 'http://192.168.0.7:8080/'
import {
api
} from '@/utils/operate.js'
/*
* @param config:{
* url - uni.uploadFile { url } 文件請求接口路徑 as String
* filePath - uni.uploadFile { filePath } 文件路徑 as String
* name - uni.uploadFile { name } as String
* header - uni.uploadFile { header } 自定義請求頭 as Object
* showToast - uni.uploadFile { showToast } 是否顯示請求結(jié)果 as Boolean
* }
*/
//封裝上傳單個圖片
export const uploadFile = (config = {}) => {
const {
url = `${api}/app/upload/image`,
filePath = null,
name = 'file',
header = {
"Content-Type": "multipart/form-data",
},
showToast = true
} = config
return new Promise((resolve, reject) => {
uni.uploadFile({
url, //文件服務(wù)器地址
filePath, //文件路徑
name,
header,
success(res) {
showToast && uni.showToast({
title: '上傳成功',
icon: "none"
});
resolve(JSON.parse(res.data))
},
fail(err) {
showToast && uni.showToast({
title: '上傳失敗',
icon: "none"
});
reject(err)
}
});
})
}
//封裝上傳多張圖片
/*
* @param config:{
* urls - 文件請求列表 [String,String...] as Array
* showOnlyOrBatch - 'Only' | 'Batch' | 'All' | 'None' 顯示提示類型 as String
* }
*/
export const uploadFileMore = (config = {}) => {
const {
urls = [],
showOnlyOrBatch = 'Only'
} = config
let fileIndex = 0;
let successList = []
return new Promise((resolve, reject) => {
(function uploadFileFun() {
uploadFile({
filePath: urls[fileIndex].url,
showToast: false
}).then(res => {
if (showOnlyOrBatch != 'None' && (showOnlyOrBatch == 'Only' ||
showOnlyOrBatch == 'All')) {
uni.showToast({
title: `正在上傳: ${fileIndex+1}/${urls.length}`,
icon: "none"
})
}
fileIndex += 1
successList.push(res.data)
if (fileIndex > urls.length - 1) {
fileIndex = 0
if (showOnlyOrBatch != 'None' && (showOnlyOrBatch == 'Batch' ||
showOnlyOrBatch == 'All')) {
uni.showToast({
title: '批量上傳成功',
icon: "none"
})
}
resolve(successList)
return
}
setTimeout(() => {
uploadFileFun(urls)
}, 1000)
}).catch((error) => {
console.log('error', error);
fileIndex = 0
uni.showToast({
title: '批量上傳失敗',
icon: "none"
});
reject(false)
})
})()
})
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-690447.html
文章來源:http://www.zghlxwxcb.cn/news/detail-690447.html
到了這里,關(guān)于uniapp小程序上傳單張/多張照片到服務(wù)器(封裝方法)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!