微信小程序:拍照與上傳


拍照與上傳

問題:上傳失敗,文件不存在。

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'

 

恕我剛接觸網絡互動,倆問題搞了一上午。小小的記錄一下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM