# 上传文件

将网页内文件对象上传至对象存储空间，如果上传至同一路径则是覆盖写

本文档适用于微信公众号 H5 中使用，如果你不是微信公众号 H5，请移步适合的文档

- [微信小程序](/minigame/dev/wxcloudrun/src/development/storage/miniapp/upload)
- [服务端和其他客户端](/minigame/dev/wxcloudrun/src/development/storage/service/upload)

## 请求参数

| 字段 | 说明 | 数据类型 | 默认值 | 必填 |
| --  | -- | -- | -- | --
| cloudPath   | 云存储路径，命名限制见[文件名命名限制](/minigame/dev/wxcloudrun/src/guide/storage/manage)| String | - | 是 |
| file   | 要上传文件资源的路径  | [File](https://developer.mozilla.org/en-US/docs/Web/API/File) | - | 是 |
| config   | 配置 | Object | - | 否 |
| success | 成功回调 | | | |
| fail | 失败回调 | | | |
| complete | 结束回调 | | | |

### config 对象定义

| 字段 | 说明 | 数据类型 |
| --  | --   | --     |
| env | 使用的环境 ID，填写后忽略 init 指定的环境 | String |

#### success 返回参数

| 字段 | 说明 | 数据类型 |
| --  | --   | --     |
| fileID | 文件 ID | String |
| statusCode | 服务器返回的 HTTP 状态码 | Number |
| errMsg | 错误信息，格式 uploadFile:ok | String |

#### fail 返回参数

| 字段 | 说明 | 数据类型 |
| --  | --   | --     |
| errCode | [错误码](/miniprogram/dev/wxcloudservice/wxcloud/reference/errcode.md) | Number |
| errMsg | 错误信息，格式 uploadFile:fail msg | String |

## 使用示例

### 1. Callback 风格

```js
cloud.uploadFile({
  cloudPath: 'example.png', // 对象存储路径，根路径直接填文件名，文件夹例子 test/文件名，不要 / 开头
  file: new File(), // 通过 input 或者 new File 获取
  config: {
    env: 'werun-id' // 需要替换成自己的微信云托管环境ID
  }
  success: res => {
    console.log(res.fileID)
  },
  fail: err => {
    console.error(err)
  }
})
```

#### 2. Promise 风格

```js
cloud.uploadFile({
  cloudPath: 'example.png', // 对象存储路径，根路径直接填文件名，文件夹例子 test/文件名，不要 / 开头
  file: new File(), // 通过 input 或者 new File 获取
  config: {
    env: 'werun-id' // 需要替换成自己的微信云托管环境ID
  }
}).then(res => {
  console.log(res.fileID)
}).catch(error => {
  console.error(err)
})
```

#### 3. 完整示例

以下示例代码写入 HTML 文件，然后在浏览器打开。

云托管不支持未登录模式，请使用以下安全实现：

1. 使用公众号有鉴权登录方式，具体参见[文档](/minigame/dev/wxcloudrun/src/development/call/h5)，需要已认证的服务号，订阅号不支持。
2. 使用普通网页上传方式，将上传链接收归于业务控制，具体参见[文档](/minigame/dev/wxcloudrun/src/development/storage/service/upload)，开发灵活但技术要求较高。

以上两种方式都可以安全的实现操作，第1个用的是权限管控（可以配置安全规则，由平台维护），第2个是自己和业务结合，由自己维护；请根据业务需要斟酌使用！

``` js
<input id="myfile" type="file"/>
<script src="https://web-9gikcbug35bad3a8-1304825656.tcloudbaseapp.com/sdk/1.3.0/cloud.js"></script>
<script>
  window.onload = async function () {
    window.c1 = new cloud.Cloud({
      resourceAppid: "小程序或公众号appid", // 微信云托管所在的「小程序/公众号」appid
      resourceEnv: "微信云托管ID", // 微信云托管环境ID，不能为空
    });
    await window.c1.init();
  }
  const myFile = document.getElementById('myfile')
  myFile.addEventListener('change', async function() {
    if(myFile.value != null) {
      const file = myFile.files[0];
      const result = await c1.uploadFile({
        cloudPath:`web/${file.name}`,
        file
      })
      console.log(result)
    }
  })
</script>
```
