tt.uploadFile
从基础库 1.0.0 开始支持
将本地文件上传到网络。 网络相关的 API 在使用前需要配置域名白名单。请参考网络请求使用说明。客户端发起一个 HTTPS POST 请求,其中 content-type
为 multipart/form-data
。
语法
tt.uploadFile(options)
参数说明
options 为 Object 类型,属性如下:
属性名 | 类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
---|---|---|---|---|---|
url | string | -- | 是 | 目标地址 | 1.0.0 |
filePath | string | -- | 是 | 本地文件路径 | 1.0.0 |
name | string | -- | 是 | HTTP 请求的文件名 | 1.0.0 |
header | object | {'content-type': 'multipart/form-data'} | 否 | 请求 Header | 1.0.0 |
formData | object | -- | 否 | 请求额外参数 | 1.0.0 |
success | function | -- | 否 | 接口调用成功的回调函数 | 1.0.0 |
fail | function | -- | 否 | 接口调用失败的回调函数 | 1.0.0 |
complete | function | -- | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) | 1.0.0 |
referer 说明
网络请求 header
中的 referer
不可设置。
其固定格式为:https://tmaservice.developer.toutiao.com?appid={appid}&version={appVersion}
,其中 appid
为小程序的 APPID,appVersion
为小程序的版本号。
user-agent 说明
网络请求 header
中的 user-agent
不可设置。
其固定格式分为:
- IOS 系统:
[系统user-agent] [宿主标识]/[宿主app版本] ToutiaoMicroApp/[基础库版本] webview/[插件版本]
。 - Android 系统:
[系统user-agent] [宿主标识]/[宿主app版本] ToutiaoMicroApp/[基础库版本] PluginVersion/[插件版本]
。
回调成功
Object 类型,属性如下:
参数 | 参数类型 | 说明 | 最低支持版本 |
---|---|---|---|
data | string | 返回数据 | 1.0.0 |
statusCode | number | 返回 HTTP 状态码 | 1.0.0 |
回调失败
Object 类型,属性如下:
参数 | 参数类型 | 类型 | 最低支持版本 |
---|---|---|---|
errMsg | string | 错误信息 | 1.0.0 |
返回值
UploadTask(上传任务对象),调用 tt.uploadFile
后返回的请求对象。
效果示例
扫码体验
请使用字节宿主APP扫码
代码示例
<!-- index.ttml -->
<view class="card-area">
<view class="display-area">
<image
tt:if="{{filePath}}"
class="image-items"
src="{{filePath}}"
mode="aspectFit"
></image>
</view>
<view class="button-area">
<button tt:if="{{filePath}}" type="primary" bindtap="uploadFile">
点击上传
</button>
<button tt:else type="primary" bindtap="chooseImage">选择图片</button>
</view>
</view>
Page({
data: {
filePath: "",
},
chooseImage() {
tt.chooseImage({
sourceType: ["album"],
count: 1, // 限制选择文件数
success: (res) => {
console.log("res", res);
this.setData({
filePath: res.tempFilePaths[0],
});
},
fail(res) {
console.log(`chooseImage调用失败`);
},
});
},
uploadFile() {
if (!this.data.filePath) {
return;
}
const id = "";
tt.uploadFile({
url: "someurl",
filePath: this.data.filePath, // 上传文件的地址
name: "filaname",
header: {
"content-type": "multipart/form-data",
cookie: "TOUTIAOID" + id, // 此处添加cookie
},
formData: {
user: "test",
},
success: (res) => {
console.log("上传成功", res);
},
fail: (err) => {
console.log("上传失败", err);
},
});
},
});
Bug & Tip
- Tip:
header
不支持设置referer
、user-agent
、content-type
字段字段。 - Tip:目前
tt.uploadFile
上传文件大小限制为 10M。 - Tip:目前
tt.uploadFile
暂不支持多文件上传,一次只能上传一个文件。 - Tip:线上版本只支持 HTTPS 协议的请求,测试版同时支持 HTTP 和 HTTPS 协议,请注意提审版本中的协议配置。
点击纠错
评价此篇文档