# 七牛文件上传

# 介绍

七牛云 (opens new window)是一个家做文件存储、CDN 内容分发、视频点播、互动直播等的云服务商,我项目主要使用其文件存储、 CDN 内容分发功能。

TIP

本文档主要介绍如何使用七牛云的 JavaScript 文件直传功能。

# 官方文档

js文件直传文档 (opens new window)

# 安装

npm install qiniu-js

# 使用

import * as qiniu from 'qiniu-js'

// 通过接口获取 `token`
const token = await getUpToken();

const key = null; // 设置为 null 时会使用文件的 hash 作为文件名

const putExtra = {
  fname: "",
  params: {},
  mimeType: ["image/png", "image/jpeg", "image/gif"],
};
const config = {
  useCdnDomain: true, //使用cdn加速
};
const observable = qiniu.upload(file, key, token, putExtra, config);

observable.subscribe({
  next: (result) => {
    // 主要用来展示进度
    // console.warn(result);
  },
  error: () => {
    this.$message.danger("上传图片失败");
    this.uploading = false;
  },

  complete: (res) => {
    this.uploading = false;

    // 将上传成功的地址提交给父组件
    this.$emit("on-change", res); 
  },
});
上次更新: 6/16/2022, 10:14:46 PM