Skip to content
关注公众号,获取新课通知

上传文件


安装

shell
npm i egg-oss --save

配置

js
// config/plugin.js
exports.oss = {
  enable: true,
  package: "egg-oss",
};

// config/config.default.js
config.multipart = {
  mode: "file",
};
// oss存储
config.oss = {
  client: {
    accessKeyId: "your access key",
    accessKeySecret: "your access secret",
    bucket: "your bucket name",
    endpoint: "oss-cn-hongkong.aliyun.com",
    timeout: "60s",
  },
};
js
// app/controller/common.js
"use strict";

const Controller = require("egg").Controller;
const fs = require("mz/fs");
const path = require("path");
class CommonController extends Controller {
  // 上传
  async upload() {
    const ctx = this.ctx;

    if (!ctx.request.files) {
      return ctx.apiFail("请先选择上传文件");
    }

    const file = ctx.request.files[0];
    // const name = 'egg-oss-demo/' + path.basename(file.filename);
    const name = "egg-oss-demo/" + ctx.genID(10) + path.extname(file.filename);
    let result;
    try {
      result = await ctx.oss.put(name, file.filepath);
    } catch (err) {
      console.log(err);
    } finally {
      await fs.unlink(file.filepath);
    }

    if (result) {
      return ctx.apiSuccess(result.url);
    }

    ctx.apiFail("上传失败");
  }
}

module.exports = CommonController;
js
// app/extend/context.js
// 生成唯一id
genID(length) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}