# uni.uploadFile(options)

将本地资源上传到开发者服务器。

推荐上传到uniCloud,uniCloud提供了更便宜CDN和更好的易用性,详见

# 参数

名称 类型 必填 默认值 描述
options UploadFileOptions -
名称 类型 必备 默认值 描述
url string - 开发者服务器 url
filePath string | null null 要上传文件资源的路径, 支持uni.env
name string | null null 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
files Array<UploadFileOptionFiles> | null null 需要上传的文件列表。
名称 类型 必备 默认值 描述
name string | null "file" multipart 提交时,表单的项目名,默认为 file,如果 name 不填或填的值相同,可能导致服务端读取文件时只能读取到一个文件。
uri string - 要上传文件资源的路径
file any | null - 要上传的文件对象
header UTSJSONObject | null null HTTP 请求 Header, header 中不能设置 Referer
formData UTSJSONObject | null null HTTP 请求中其他额外的 form data
timeout number | null 120000 超时时间,单位 ms
success (result: UploadFileSuccess) => void | null null 成功返回的回调函数
fail (result: UploadFileFail) => void | null null 失败的回调函数
complete (result: any) => void | null null 结束的回调函数(调用成功、失败都会执行)
# UploadFileOptionFiles 兼容性
Android iOS web
file 3.9 4.11 4.0
# UploadFileSuccess 的属性值
名称 类型 必备 默认值 描述
data string - 开发者服务器返回的数据
statusCode number - 开发者服务器返回的 HTTP 状态码
# UploadFileFail 的属性值
名称 类型 必备 默认值 描述
errCode 5 | 1000 | 100001 | 100002 | 600003 | 600009 | 602001 - 错误码
- 5 接口超时
- 1000 服务端系统错误
- 100001 json数据解析错误
- 100002 错误信息json解析失败
- 600003 网络中断
- 600009 URL格式不合法
- 602001 request系统错误
errSubject string - 统一错误主题(模块)名称
data any | null - 错误信息中包含的数据
cause Error | null - 源错误信息,可以包含多个错误,详见SourceError
errMsg string - -

# 返回值

类型
UploadTask

# UploadTask 的方法

# abort()

中断上传任务。

# abort 兼容性
Android iOS web
3.9 4.11 4.0
# 参见

# onProgressUpdate(callback)

监听上传进度变化。

# 参数
名称 类型 必填 默认值 描述
callback (result: OnProgressUpdateResult) => void -
# OnProgressUpdateResult 的属性值
名称 类型 必备 默认值 描述
progress number - 上传进度百分比
totalBytesSent number - 已经上传的数据长度,单位 Bytes
totalBytesExpectedToSend number - 预期需要上传的数据总长度,单位 Bytes
# onProgressUpdate 兼容性
Android iOS web
3.9 4.11 4.0
# 参见

# uploadFile 兼容性

Android iOS web
3.9 4.11 4.0

# 参见

相关 Bug

# 示例

hello uni-app x

Template

Script

<template>
  <!-- #ifdef APP -->
  <scroll-view class="page-scroll-view">
  <!-- #endif -->
    <view>
      <page-head :title="title"></page-head>
      <view class="uni-padding-wrap uni-common-mt">
        <view class="demo">
          <image v-if="imageSrc" :src="imageSrc" class="image" mode="widthFix"></image>
          <text v-else class="uni-hello-addfile" @click="chooseImage">+ 选择图片</text>
        </view>
      </view>
    </view>
  <!-- #ifdef APP -->
  </scroll-view>
  <!-- #endif -->
</template>


<style>
  .image {
    width: 100%;
  }

  .demo {
    background: #fff;
    padding: 25px;
    justify-content: center;
    align-items: center;
  }

  .uni-hello-addfile {
    text-align: center;
    background: #fff;
    padding: 25px;
    margin-top: 10px;
    font-size: 19px;
    color: #808080;
  }
</style>

# 通用类型

# GeneralCallbackResult

名称 类型 必备 默认值 描述
errMsg string - 错误信息

注意

  • web端上传文件时仅能使用downloadFile、chooseImage等返回文件对象的接口的返回值作为要上传的文件