uniapp上传单张/多张照片到服务器(封装方法)
import {
api
} from '@/utils/operate.js'
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,
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)
}
});
})
}
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)
})
})()
})
}