Taro.uploadFile(option)
Uploads local resources to the server. The client initiates an HTTPS POST request with content-type
being multipart/form-data
. Read related instructions before use.
Type
(option: Option) => Promise<SuccessCallbackResult & UploadTask> & UploadTask
Parameters
Option
Property | Type | Required | Description |
---|---|---|---|
url | string | Yes | Developer server URL |
filePath | string | Yes | Path to upload a file |
name | string | Yes | Key of the file. The developer can get the binary content of the file on the server via this key. |
header | Record<string, any> | No | HTTP request Header. Referer is not available in Header. |
formData | Record<string, any> | No | Additional form data in the HTTP request |
timeout | number | No | Timeout time, in ms |
fileName | string | No | Name of the uploaded file (Only H5) |
complete | (res: CallbackResult) => void | No | The callback function used when the API call completed (always executed whether the call succeeds or fails) |
fail | (res: CallbackResult) => void | No | The callback function for a failed API call |
success | (res: CallbackResult) => void | No | The callback function for a successful API call |
API Support
API | WeChat Mini-Program | H5 | React Native |
---|---|---|---|
Option.fileName | ✔️ |
SuccessCallbackResult
Property | Type | Description |
---|---|---|
data | string | Data returned by the developer server |
statusCode | number | HTTP status code returned by the developer server |
errMsg | string | Call result |
Sample Code
Example 1
Taro.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
Taro.uploadFile({
url: 'https://example.weixin.qq.com/upload', //This value for demonstration purposes only is not a real API URL.
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})
Example 2
const uploadTask = Taro.uploadFile({
url: 'https://example.weixin.qq.com/upload', //This value for demonstration purposes only is not a real API URL.
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success: function (res){
var data = res.data
//do something
}
})
uploadTask.onProgressUpdate((res) => {
console.log('Upload progress', res.progress)
console.log('The length of uploaded data', res.totalBytesSent)
console.log('The length of data expected to be uploaded', res.totalBytesExpectedToSend)
})
uploadTask.abort() // Cancel upload tasks
API Support
API | WeChat Mini-Program | Baidu Smart-Program | Alipay Mini-Program | H5 | React Native |
---|---|---|---|---|---|
Taro.uploadFile | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |