上傳
uploadFile
TIP
該API使用方法為: UploadTask wx.uploadFile(Object object)
功能說明: 將本地資源上傳到服務器。 用戶端發起一個HTTPS POST請求,其中content-type為multipart/form-data。 使用前請注意閱讀相關說明。
參數及說明: Object object。
内容 類型 預設值 必填 說明 url string - 是 開發者伺服器地址 filePath string - 是 要上傳文件資源的路徑(本地路徑) name string - 是 文件對應的key,開發者在服務端可以通過這個key獲取文件的二進位內容 header object - 否 HTTP請求Header,Header中不能設定Referer formData object - 否 HTTP請求中其他額外的form data success Function - 否 接口調用成功的回呼函數 fail Function - 否 接口調用失敗的回呼函數 complete Function - 否 接口調用結束的回呼函數(無論成功與否都執行) object.success回呼函數參數: Object res。
内容 類型 說明 data string 開發者服務器返回的數據 statusCode number 開發者服務器返回的HTTP狀態碼 返回值: UploadTask ,一個可以監聽上傳進度進度變化的事件和取消上傳的對象。
示例代碼:
wx.chooseImage({
success (res){
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', // This is merely an example and not an actual interface address.
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})UploadTask
.abort
TIP
該API使用方法為: UploadTask.abort()
- 功能說明: 中斷上傳任務。
.onProgressUpdate
TIP
該API使用方法為: UploadTask.onProgressUpdate(function listener)
功能說明: 監聽上傳進度變化事件。
參數及說明: function listener,上傳進度變化事件的監聽函數,參數Object.res如下:
内容 類型 說明 progress number 下載進度百分比 totalBytesWritten number 已經下載的數據長度,單位Bytes totalBytesExpectedToWrite number 預期需要下載的數據總長度,單位Bytes
.offProgressUpdate
TIP
該API使用方法為: UploadTask.offProgressUpdate(function listener)
功能說明: 移除上傳進度變化事件的監聽函數。
參數及說明: function listener, onProgressUpdate傳入的監聽函數。 不傳此參數則移除所有監聽函數。
示例代碼:
const listener = function (res) { console.log(res) }
DownloadTask.onProgressUpdate(listener)
DownloadTask.offProgressUpdate(listener) // Pass the same function object used for listening..onHeadersReceived
TIP
該API使用方法為: UploadTask.onHeadersReceived(function listener)
功能說明: 監聽HTTP Response Header事件。 會比請求完成事件更早。
參數及說明: function listener,HTTP Response Header事件的監聽函數。
内容 類型 說明 header Object 開發者服務器返回的HTTP Response Header
.offHeadersReceived
TIP
該API使用方法為: UploadTask.offHeadersReceived(function listener)
功能說明: 移除HTTP Response Header事件的監聽函數。
參數及說明: function listener, onHeadersReceived傳入的監聽函數。 不傳此參數則移除所有監聽函數。
示例代碼:
const listener = function (res) { console.log(res) }
UploadTask.onHeadersReceived(listener)
UploadTask.offHeadersReceived(listener) // Pass the same function object used for listening.const uploadTask = wx.uploadFile({
url: 'http://example.weixin.qq.com/upload', // This is merely an example and not an actual interface address.
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
uploadTask.onProgressUpdate((res) => {
console.log('Upload progress', res.progress)
console.log('Length of already uploaded data', res.totalBytesSent)
console.log('Total length of data expected to be uploaded', res.totalBytesExpectedToSend)
})
uploadTask.abort() // Aborts upload task