uniapp上传单张/多张照片到服务器(封装方法)
//operate.js文件内容
//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 } 是否显示请求结果 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, //文件服务器地址
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)
})
})()
})
}
文章来源地址https://www.toymoban.com/news/detail-690447.html
文章来源:https://www.toymoban.com/news/detail-690447.html
到了这里,关于uniapp小程序上传单张/多张照片到服务器(封装方法)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!