uniApp、微信小程序上传单个文件及多个文件

使用官方api - uni.uploadFile

这是单个文件上传写法

/**
 * 单个上传文件方法
 */
fun_GetFileUpload(){
	var that = this;
	// 请求接口
	uni.uploadFile({
		url: "url", // 后端接口
		formData: {}, // 需要上传的参数
		filePath: "", // 文件临时地址
		name: 'file', // 后端接收的文件名
		header: {}, // 请求头
		success: res => {
			console.log(res); // 打印返回内容
			// 判断请求是否成功
			if (res.statusCode === 200) {
			    // 判断是否成功
				if(JSON.parse(res.data).result){
					// 成功的场合
					// 提示
					uni.showToast({
						title: JSON.parse(res.data).msg,
						icon: 'success',
					});
				}else{
					// 提示
					uni.showToast({
					    title: JSON.parse(res.data).msg,
						icon: 'error',
					});
				}
			} else {
				// 提示
				uni.showToast({
					title: res.errMsg,
					icon: 'error',
				});
			}
		},
		fail: err => {
			console.log(err)
		}
	});},

这是上传多个文件写法

由于没有多个上传文件的方法,目前只能通过遍历的方式来进行多文件上传

/**
 * 遍历上传文件
 */
fun_TraversalFile(){
	var that = this;
	var frequency = 0; // 这个用于判断是否遍历结束
	// 遍历
	that.fileList.map(e=>{
		frequency ++; // 遍历一次+1
		// 请求接口
		uni.uploadFile({
			url: "", // 后端接口
			formData: { }, // 需要上传的参数
			filePath: "", // 文件临时地址
			name: 'file', // 后端接收的文件名
			header: {}, // 请求头
			success: res => {
				console.log(res); // 打印返回值
				// 判断请求是否成功
				if (res.statusCode === 200) {
					// 判断是否成功
					if(JSON.parse(res.data).result){ 
						// 成功的场合
						// 判断执行结束
						if(frequency === that.fileList.length){ // 判断遍历次数是否与需要上传的文件数组长度相同
							// 提示
							uni.showToast({
								title: JSON.parse(res.data).msg,
								icon: 'success',
							});
						}
					}else{
						// 提示
						uni.showToast({
							title: JSON.parse(res.data).msg,
							icon: 'error',
						});
					}
				} else {
					// 提示
					uni.showToast({
						title: res.errMsg,
						icon: 'error',
					});
				}
			},
			fail: err => {
				console.log(err)
			}
		});
	})
},

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值