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)
				}
			});
		});
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值