微信小程式:拍照與上傳
阿新 • • 發佈:2018-11-28
拍照與上傳
問題:上傳失敗,檔案不存在。
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'>
<view class='centeralign'> <button wx:if='{{!photoTaken}}' type="primary" width='80%' bindtap="takePhoto">開始識別</button>
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'
恕我剛接觸網路互動,倆問題搞了一上午。小小的記錄一下。