uniapp文件上传封装使用(含超时设置:大文件上传失败原因)
·
上传超过5M的附件,容易出现上传失败的问题,经排查为前端超时问题导致,补充timeout设置为30s,就解决这个问题了~
export default class FileUploader {
// 包含文件类型判断和超大附件处理版本
static async uploadFileNew(extension ?: string[]) {
return new Promise((resolve) => {
uni.chooseFile({
count: 1, // 默认选择一个文件
// type: 'all', // 文件类型
extension: extension || ['png', 'jpg', 'jpeg', 'pdf'], // 允许选择的文件后缀
success(res) {
uni.showLoading({
title: '文件上传中…',
mask: true
})
// 判断文件大小限制
const tempFilePaths = res.tempFiles[0];
let resSize =( res.tempFiles[0].size)/1024/1024;
console.log(res, '上传的res====')
if(resSize > 10){
uni.showToast({
title: "上传的图片或者pdf大小不超过10m",
icon: 'none',
duration: 2000,
mask: true
})
return
}
// 判断文件格式
const resType = res.tempFiles[0].name.split('.')[1]
if (!extension.includes(resType)) {
uni.showToast({
title: "文件格式有误,请重新选择",
icon: 'none',
duration: 2000,
mask: true
})
return
}
// 底部代码通过设置timeout可处理文件过大的问题
uni.uploadFile({
url:'你的接口地址',
filePath: tempFilePaths.path,
name: 'file',
timeout: 300000,
// 其他参数...
}).
then(uploadFileRes => {
uni.hideLoading()
const res = JSON.parse(uploadFileRes.data)
resolve(res.data);
}).catch(err => {
uni.hideLoading()
uni.showToast({
title: '上传失败',
icon: 'error'
});
console.log('1错误原因', err)
});
},
fail(err) {
uni.hideLoading()
uni.showToast({
title: '上传失败',
icon: 'error'
});
console.log('2错误原因', err)
}
});
});
}
}
更多推荐
所有评论(0)