微信小程序 图片的上传

错误示范

/*从相册中选择文件  微信小程序*/
	chooseImage(){
		wx.chooseMedia({
		  count: 9,
		  mediaType: ['image'],
		  sourceType: ['album'],
		  success(res) {
			  wx.request({
				  url:"发送的端口占位符",
				  data:res.tempFiles[0].tempFilePath,
				  method:'POST',
					  
				  success(res){//请求成功后应该返回的是分割完成的图片(Arraybuffer 类型)
					  res.data
				  },fail(err){
					  console.error('图片发送请求错误:'err.errMsg+',错误码:'+err.error,)
				  }
			  })

		  }
		})
	},

两个致命错误(是菜鸟勿笑):

  • 首先wx.request的data是用来发送文本数据的,最多可以发送Arraybuffer的音频数据,这里应该使用 wx.uploadFile来上传图片到后端。
  • 其次res.tempFiles[0].tempFilePath表示的也只是图片的临时路径,发送图片应该将图片文件转换成 FormData 对象。
/*从相册中选择文件  微信小程序*/
	chooseImage(){
		  wx.chooseMedia({
		    count: 1, // 选择图片的数量,只需要选择一张图片
		    mediaType: ['image'],
		    sourceType: ['album'],
		    success(res) {
		      // 只关心第一张图片
		      const tempFilePath = res.tempFiles[0].tempFilePath;
		      const formData = new FormData();
		      formData.append('file', {
		        name: 'image.jpg', // 指定文件名
		        uri: tempFilePath,
		        type: 'image/jpeg', // 文件类型
		      });
		
		      wx.uploadFile({
		        url: "发送的端口占位符", 
		        filePath: tempFilePath,
		        name: 'file', // 与后端约定的文件对应的 key, 
		        formData: formData, // 如果有额外的表单数据,可以在这里添加
		        success(uploadRes) {
		          console.log('图片上传成功', uploadRes);
		          // 这里可以处理上传成功后的逻辑,比如解析服务器返回的数据
		        },
		        fail(err) {
		          console.error('图片上传请求错误:', err.errMsg);
		        }
		      });
		    },
		    fail(err) {
		      console.error('选择图片失败:', err.errMsg);
		    }
		  });
		
	},

打脸了,

在微信小程序中,FormData 不是一个内置的全局对象,所以你会看到 ReferenceError: FormData is not defined 这样的错误。在小程序中,你不需要创建 FormData 对象,因为 wx.uploadFile 方法会自动处理文件的上传。

	chooseImage(){
		  wx.chooseMedia({
		    count: 1, // 选择图片的数量,只需要选择一张图片
		    mediaType: ['image'],
		    sourceType: ['album'],
		    success(res) {
		      // 只关心第一张图片
		      const tempFilePath = res.tempFiles[0].tempFilePath;
		      wx.uploadFile({
		        url: "http://127.0.0.1:5000/upimage", 
		        filePath: tempFilePath,
		        name: 'file', // 与后端约定的文件对应的 key, 
		        success(uploadRes) {
		          console.log('图片上传成功', uploadRes);
		          // 这里可以处理上传成功后的逻辑,比如解析服务器返回的数据
		        },
		        fail(err) {
		          console.error('图片上传请求错误:', err.errMsg);
		        }
		      });
		    },
		    fail(err) {
		      console.error('选择图片失败:', err.errMsg);
		    }
		  });
		
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值