微信小程序:拍照与上传

拍照与上传

问题:上传失败,文件不存在。

uploadFile:fail createUploadTask:fail file not found

原因:文件名赋值的时候使用了错误的变量,或者赋值为空了。(<--我的问题)

filePath: '',//should be path,

发现:

调试文件名的过程中,发现中间存储路径 res.tempImagePath 实际上是一个伪网址,如下,打不开

http://tmp/wx802d50225b02b0ae.o6zAJs5cCyOosBERHAwPhhDB5kFw.RMSIQHWogGyXd815604e9017a14b30adb2a57b01e883.jpg

刚开始,还以为需要先wx.saveFile,然后才可以上传,结果发现不是。

这个路径时可以直接用在wx.uploadFile中的。

代码:


.centeralign{
align-content: center;
align-items: center;
text-align: center;
margin: 10px;
}

<view class='centeralign'>
<camera wx:if='{{!photoTaken}}' device-position="back" flash="off" binderror="error" style="width: 100%; height: 220px;" />
<image wx:if='{{photoTaken}}' mode="widthFix" style="width:100%" src="{{src}}" />
</view>

<view class='centeralign'>
<button wx:if='{{!photoTaken}}' type="primary" width='80%' bindtap="takePhoto">开始识别</button>
<button wx:if='{{photoTaken}}' type="default" width='80%' bindtap="restartCamera">重新拍照</button>
</view>
 

takePhoto() {

var that=this;
const ctx = wx.createCameraContext();
ctx.takePhoto({
quality: 'high',
success: (res) => {

console.log('temp photo path:',res.tempImagePath);
this.setData({
src: res.tempImagePath,
photoTaken:true,
})
      //插入上传代码段
 
}
})

},
restartCamera(){
this.setData({
src: '',
photoTaken: false,
})
},
error(e) {
console.log(e.detail)
},

//upload file js
//--------
wx.showLoading({
title: '上传中...',
})
wx.uploadFile({
url: 'theURL',
filePath: path,
name: name, //name should be the file key in formData,
header: header,
method: 'POST',
formData: {
uuid: imgId,
},
success: res => {
successCallback(res);
},
fail: err => {
wx.hideLoading();
wx.showToast({
title: '请求超时',
icon: 'loading',
duration: 2000
});
if (fail) {
if (failCallback != null) {
failCallback(err);
}
}
},
complete: function () {
wx.hideLoading();
}

})
//--------

另一个问题,在将图片POST到WEB API的过程中,总是报错,文件未上传。

后来返现,wx.uploadFile中的参数name,不是指文件名,而是指POST的FORM-DATA中的Key值。

比如,有如下API用POSTMAN测试是OK的,它需要的form-data中的Key是file,那么,这个name就必须设置成'file'

恕我刚接触网络互动,俩问题搞了一上午。小小的记录一下。

猜你喜欢

转载自www.cnblogs.com/jiceberg420/p/10031277.html