1.0.8 • Published 3 years ago

@zegoweb/z-upload v1.0.8

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

媒资断点续传SDK

1、 安装

# 方式一:npm/pnpm/yarn 安装
pnpm install @zegoweb/z-upload -S
# 方式二:本地SDK包,接入使用

2、使用

// ES6
import { ZUpload } from '@zegoweb/z-upload';
const uploader = new ZUpload({});

// UMD
const { ZUpload } =  require('@zegoweb/z-upload');
const uploader = new ZUpload({});

3、错误码

  • 协议层:(常见)

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

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

4、API说明

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

相关参数说明:

初始化: new ZUpload(uplodConfig[,uploadOptions]);

  • uploadConfig:

    • 类型:Object
    • 说明:文件上传初始化参数
    参数参数类型是否必填参数说明
    tokenstring请求Token
    apiPrefixstring上传后端API接口前缀
    authNamestringHeaders中鉴权名称,Authorization/token(默认)...
    timeoutnumber上传请求超时时间,单位毫秒,默认:0
  • uploadOptions

    • 类型:Object

    • 说明:上传额外参数

    • 备注:chunkSize 默认(auto),将采取动态处理分片大小,处理规则如下:

      • <10M 单个分片大小为5M;

      • >50M且<200M 单个分片大小为10M;

      • >200M且<1G 单个分片大小为50M;

      • >1G且<2G 单个分片为100M;

      • >2G 单个分片为200M

    参数参数类型是否必填参数说明
    chunkSizenumber | ‘auto’文件单个分片大小,单位Byte,必须大于5M,默认: ‘auto’
    needAuthnumber存储到是否需要授权的桶中,0: 不授权,1(默认): 授权
const token = '710524909276631040',
  apiPrefix = 'http://mm-test.zegonetwork.com:30002/api/v1/storage/breakpoint',
	chunkSize = 1024 * 1024 * 10;
const uploader = new ZUpload({token, apiPrefix}, {chunkSize});

上传文件:uploader.startUpload(File)

  • File:
    • 类型:File
    • 说明:选取文件(单个)
<template>
	<div class="contain">
		<input type="file" @change="onFileAdded" multiple>
  </div>
</template>

<script>
  const token = '710524909276631040',
  apiPrefix = 'http://mm-test.zegonetwork.com:30002/api/v1/storage/breakpoint',
	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

    • 说明:上传状态、进度条、错误等信息

    • 正确值:

      类型说明
      statusCodenumber状态值: 0:切片解析中;1: 解析完成 2:上传中;3:暂停上传中;4:暂停分片中;5:取消上传;6:上传完成;
      statusTextstring状态值对应文案
      progressnumber进度百分比
      spendnumber耗时(秒)
      fileInfoobject上传完成文件信息
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()

  • 多个文件上传
// 暂停
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案例

vue2:

<template>
<div class="contain">
  <div class="native-upload">
    <input type="file" @change="onFileAdded" multiple>
    <div class="table-item" v-for="(item, index) in fileList" :key="index">
      <div class="left">
        <p>{{item.name}}</p>
      </div>
      <div class="right">
        <p>文件大小:<span class="hightlight">{{item.size}}</span></p>
        <p>文件处理状态:<span class="hightlight">{{item.statusText}}</span></p>
        <p>文件上传进度:<span class="hightlight">{{item.progress}}%</span></p>
        <button @click="handlePause(index)">暂停</button>
        <button @click="handleResume(index)">继续</button>
        <button @click="handleCancel(index)">取消</button>
      </div>
    </div>
    <div class="table-message" v-if="messageList.length">
      <p class="hightlight" v-for="(item, index) in messageList" :key="index">{{item}}</p>
    </div>
  </div>
</div>
</template>

<script>
  import { ZUpload } from '@zegoweb/z-upload'

  export default {
    data () {
      return {
        fileList: [],
        token: '710524909276631040',
        apiPrefix: 'http://mm-test.zegonetwork.com:30002/api/v1/storage/breakpoint',
        messageList: [],
      }
    },
    methods: {
        // 添加文件
        onFileAdded(e) {
          // 测试!先清空文件
          this.fileList = [];
          this.messageList = [];
          const fileArr = e.target.files;
          for (let index = 0, len = fileArr.length; index < len; index++) {
            // 初始化文件上传管理器,并监听
            const uploader = new ZUpload({token: this.token, apiPrefix: this.apiPrefix});
            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}`);
                }
              }
            }) 
            this.fileList.push({
              index,
              uploader,
              name: fileArr[index].name,
              size: fileArr[index].size,
              file: fileArr[index],
              progress: 0,
              statusCode: 0,
              statusText: 0,
            });
            uploader.startUpload(fileArr[index]);
          }
        },

        // 暂停
        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});
          }
        }
    }
  }
</script>

<style>
  .table-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #c2c2c2;
  }
  .left {
    display: flex;
    align-items: center;
  }
  .right {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .hightlight {
    font-weight: bold;
    color: red;
  }
</style>

如果提供了对应(其它)Demo源码, 具体可见demo示例

1.0.8

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago