# zego-wx-upload

> Meida web break-point upload for Javascript in wechat miniprogram

Latest version **0.0.11** (published 2022-02-22) · MIT license · 0 weekly downloads

## Install

```sh
npm install zego-wx-upload
pnpm add zego-wx-upload
yarn add zego-wx-upload
bun add zego-wx-upload
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.11 |
| Published | 2022-02-22 |
| First published | 2022-02-22 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=12.2.0 |
| Dependencies | 2 |
| Unpacked size | 1.3 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | failteku |
| Maintainers | zegoweb |
| Keywords | 断点上传, minio, miniprogram, 微信, 小程序 |

## Links

- npm: https://www.npmjs.com/package/zego-wx-upload
- npm.io page: https://npm.io/package/zego-wx-upload

## Dependencies (2)

- [mitt](https://npm.io/package/mitt.md) ^3.0.0
- [spark-md5](https://npm.io/package/spark-md5.md) ^3.0.2

## Recent versions

- 0.0.11 (latest) — 2022-02-22
- 0.0.10 — 2022-02-22
- 0.0.9 — 2022-02-22
- 0.0.8 — 2022-02-22
- 0.0.7 — 2022-02-22
- 0.0.6 — 2022-02-22
- 0.0.5 — 2022-02-22
- 0.0.4 — 2022-02-22
- 0.0.3 — 2022-02-22
- 0.0.2 — 2022-02-22
- 0.0.1 — 2022-02-22

## README

## 媒资断点续传 - 微信小程序 SDK

### 1、 安装

```shell
# 方式一：npm/pnpm/yarn 安装
pnpm install @zegoweb/wx-upload -S
# 方式二：本地SDK包，接入使用
```

#### 2、使用

```javascript
// ES6
const token = "zego-token";
const apiPrefix = "zego-apiPrefix";
import { WXUpload } from "@zegoweb/wx-upload";
const uploader = new WXUpload(
  { token, apiPrefix },
  { chunkSize: 1024 * 1024 * 5 }
);

// UMD
const token = "zego-token";
const apiPrefix = "zego-apiPrefix";
const { WXUpload } = require("@zegoweb/wx-upload");
const uploader = new WXUpload(
  { token, apiPrefix },
  { chunkSize: 1024 * 1024 * 5 }
);
```

### 3、错误码

- 协议层：(常见)

  | 错误码 | 错误信息          |
  | ------ | ----------------- |
  | 400    | 请求错误          |
  | 401    | 未授权，请登录    |
  | 403    | 拒绝访问          |
  | 404    | 请求地址出错      |
  | 408    | 请求超时          |
  | 500    | 服务器内部错误    |
  | 501    | 服务未实现        |
  | 502    | 网关错误          |
  | 503    | 服务不可用        |
  | 504    | 网关超时          |
  | 505    | HTTP 版本不受支持 |

- 业务层：(常见)

  | 错误码 | 错误信息         |
  | ------ | ---------------- |
  | -1     | 网络异常         |
  | -2     | 网络超时         |
  | -3     | 请求失败         |
  | -100xx | 后端其它错误信息 |

### 4、API 说明

```javascript
// npm 安装使用
import { WXUpload } from '@zegoweb/wx-upload';
// 初始化上传
const uploader = new ZUpload(uplodConfig[，uploadOptions]);
// 开始上传
uploader.startUpload(WXFile)
// 暂停上传
uploader.pauseUpload()
// 续传
uploader.resumeUpload()
// 取消
uploader.cancelUpload();
// 获取上传状态、进度条、错误
uploader.emitter.on("*", (type, info) => {
  if(type === 'data') {
    // 获取上传状态、进度条等信息
    console.log(info);
  }
  if(type === 'error') {
    // 获取错误信息
    console.log(info);
  }
})
```

相关参数说明：

#### 初始化： `new WXUpload(uplodConfig[，uploadOptions]);`

- `uploadConfig`:

  - 类型：`Object`
  - 说明：文件上传初始化参数

  | 参数      | 参数类型 | 是否必填 | 参数说明                            |
  | --------- | -------- | -------- | ----------------------------------- |
  | token     | string   | 是       | 请求 Token                          |
  | apiPrefix | string   | 是       | 上传后端 API 接口前缀               |
  | timeout   | number   | 否       | 上传请求超时时间，单位毫秒，默认：0 |

- `uploadOptions`：

  - 类型：`Object`

  - 说明：上传额外参数

  - 备注：默认（`auto`）,将采取动态处理分片大小，处理规则如下：

    - _<10M 单个分片大小为 5M；_

    - _>50M 且<200M 单个分片大小为 10M；_

    - _>200M 且<1G 单个分片大小为 50M；_

    - _>1G 且<2G 单个分片为 100M；_

    - _>2G 单个分片为 200M_

  | 参数      | 参数类型         | 是否必填 | 参数说明                                               |
  | --------- | ---------------- | -------- | ------------------------------------------------------ |
  | chunkSize | number \| ‘auto’ | 否       | 文件单个分片大小，单位 Byte，必须大于 5M，默认: ‘auto’ |

```javascript
const token = "710524909276631040",
  apiPrefix = "http://mm-test.zegonetwork.com:30002/api/v1/storage/breakpoint",
  chunkSize = 1024 * 1024 * 10;
const uploader = new WXUpload({ token, apiPrefix }, { chunkSize });
```

#### 上传文件：`uploader.startUpload(File)`

- `File`:
  - 类型：`File`
  - 说明：选取文件(单个)

```vue
<template>
  <div class="contain">
    <input type="file" @change="onFileAdded" multiple />
  </div>
</template>

<script>
const token = "zego-token",
  apiPrefix = "zego-apiPrefix",
  chunkSize = 1024 * 1024 * 10;
export default {
  methods: {
    onFileAdded(e) {
      const uploader = new ZUpload({ token, apiPrefix }, { chunkSize });
      const file = e.target.files[0];
      uploader.startUpload(file);
    },
  },
};
</script>
```

#### 监听数据：`uploader.emitter.on("*", (type, info) => {}`

- 监听 `type`:

  - 类型：`enum`

  - 说明：监听的错误类型

    | 枚举值 | 说明                 |
    | ------ | -------------------- |
    | data   | 上传过程中，正确类型 |
    | error  | 上传过程中，报错类型 |

- 监听 `info`:

  - 类型： `Object`

  - 说明：上传状态、进度条、错误等信息

  - 正确值：

    | 值         | 类型   | 说明                                                                                             |
    | ---------- | ------ | ------------------------------------------------------------------------------------------------ |
    | statusCode | number | 状态值: 0:切片解析中；1: 解析完成 2:上传中；3:暂停上传中；4:暂停分片中；5:取消上传；6:上传完成； |
    | statusText | string | 状态值对应文案                                                                                   |
    | progress   | number | 进度百分比                                                                                       |
    | spend      | number | 耗时（秒）                                                                                       |
    | fileInfo   | object | 上传完成文件信息                                                                                 |

```javascript
uploader.emitter.on("*", (type, info) => {
  if (type === "data") {
    const { statusCode, statusText, progress, spend, fileInfo } = info;
    [this.fileList[index].statusText, this.fileList[index].progress] = [
      statusText,
      progress,
      spend,
      fileInfo,
    ];
    if (progress === 100) {
      this.messageList.push(
        `${this.fileList[index].name} 上传完成, 耗时: ${
          spend ? spend + "s" : "秒传"
        }, 存储文件名：${fileInfo.fileId}, 存储桶：${fileInfo.bucket}`
      );
    } else {
      this.messageList.push(
        `${this.fileList[index].name} 上传, 当前状态码: ${statusCode}, 当前状态文字: ${statusText}`
      );
    }
  }
  if (type === "error") {
    const { code, message } = info;
    if (code === -1) {
      this.fileList[index].statusText = "上传错误";
      this.messageList.push(
        `${this.fileList[index].name} 上传失败, ${message}`
      );
    }
  }
});
```

#### 操作事件：`uploader.pauseUpload()`/`uploader.resumeUpload()`/`uploader.cancelUpload()`

- 多个文件上传

```javascript
// 暂停
async handlePause(index) {
  try {
    const res = await this.fileList[index].uploader.pauseUpload();
    console.log({res});
    const {statusCode, statusText, progress} = res;
    [this.fileList[index].statusText, this.fileList[index].progress] = [statusText, progress];
    this.messageList.push(`${this.fileList[index].name} 上传, 当前状态码: ${statusCode}, 当前状态文字: ${statusText}`)
  } catch (error) {
    console.log({error});
  }
},
// 续传
async handleResume(index) {
  try {
    await this.fileList[index].uploader.resumeUpload();
  } catch (error) {
    console.log({error});
  }
},
// 取消
async handleCancel(index) {
  try {
    const res = await this.fileList[index].uploader.cancelUpload();
    const {statusCode, statusText, progress} = res;
    [this.fileList[index].statusText, this.fileList[index].progress] = [statusText, progress];
    this.messageList.push(`${this.fileList[index].name} 上传, 当前状态码: ${statusCode}, 当前状态文字: ${statusText}`)
  } catch (error) {
    console.log({error});
  }
}
```

### 5、Demo 案例

---
_Source: https://npm.io/package/zego-wx-upload · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
