title: Taro.uploadFile(option)

sidebar_label: uploadFile

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.

Reference

Type

  1. (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

  1. Taro.chooseImage({
  2. success (res) {
  3. const tempFilePaths = res.tempFilePaths
  4. Taro.uploadFile({
  5. url: 'https://example.weixin.qq.com/upload', //This value for demonstration purposes only is not a real API URL.
  6. filePath: tempFilePaths[0],
  7. name: 'file',
  8. formData: {
  9. 'user': 'test'
  10. },
  11. success (res){
  12. const data = res.data
  13. //do something
  14. }
  15. })
  16. }
  17. })

Example 2

  1. const uploadTask = Taro.uploadFile({
  2. url: 'https://example.weixin.qq.com/upload', //This value for demonstration purposes only is not a real API URL.
  3. filePath: tempFilePaths[0],
  4. name: 'file',
  5. formData:{
  6. 'user': 'test'
  7. },
  8. success: function (res){
  9. var data = res.data
  10. //do something
  11. }
  12. })
  13. uploadTask.onProgressUpdate((res) => {
  14. console.log('Upload progress', res.progress)
  15. console.log('The length of uploaded data', res.totalBytesSent)
  16. console.log('The length of data expected to be uploaded', res.totalBytesExpectedToSend)
  17. })
  18. uploadTask.abort() // Cancel upload tasks

API Support

API WeChat Mini-Program Baidu Smart-Program Alipay Mini-Program H5 React Native
Taro.uploadFile ✔️ ✔️ ✔️ ✔️ ✔️