koa实现七牛上传

2021-08-16 12:20:13

记录如何用 koa 实现七牛上传

# 安装依赖

  • busboy
  • qiniu

# 实现详解

  1. 引入必要的模块

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const path = require('path');
const fs = require('fs');
const Busboy = require('busboy');
const qiniu = require('qiniu');
  1. 添加上传请求路由处理
router.post('/upload', async (ctx, next) => {
  const serverPath = path.join(__dirname, './uploads/');
  // 获取上传的文件
  const result = await uploadFile(ctx, {
    fileType: 'tmp',
    path: serverPath,
  });
  const imgPath = path.join(serverPath, result.imgPath);
  // 上传到七牛
  const qiniu = await upToQiniu(imgPath, result.imgKey);

  ctx.body = {
    fileUrl: `${qiniuConfig.domain}/${qiniu.key}`,
  };
  await next();
});
  1. 将接受到的文件存至本地
// 上传到本地服务器
function uploadFile(ctx, options) {
  const _emmiter = new Busboy({ headers: ctx.req.headers });
  const fileType = options.fileType;
  const filePath = path.join(options.path, fileType);
  const confirm = mkdirsSync(filePath);
  if (!confirm) {
    return;
  }
  console.log('start uploading...');
  return new Promise((resolve, reject) => {
    _emmiter.on('file', function(
      fieldname,
      file,
      filename,
      encoding,
      mimetype
    ) {
      const fileName = Rename(filename);
      const saveTo = path.join(path.join(filePath, fileName));
      file.pipe(fs.createWriteStream(saveTo));
      file.on('end', function() {
        resolve({
          imgPath: `/${fileType}/${fileName}`,
          imgKey: fileName,
        });
      });
    });

    _emmiter.on('finish', function() {
      console.log('finished...');
    });

    _emmiter.on('error', function(err) {
      console.log('err...');
      reject(err);
    });

    ctx.req.pipe(_emmiter);
  });
}

const mkdirsSync = (dirname) => {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
  return false;
};
  1. 上传至七牛存储桶
// 上传到七牛
function upToQiniu(filePath, key) {
  const accessKey = qiniuConfig.accessKey; // 七牛accessKey
  const secretKey = qiniuConfig.secretKey; // 七牛secretKey
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

  const options = {
    scope: qiniuConfig.scope, // 七牛存储bucketName
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);
  const uploadToken = putPolicy.uploadToken(mac);

  const config = new qiniu.conf.Config();
  config.zone = qiniu.zone.Zone_z2;
  const localFile = filePath;
  const formUploader = new qiniu.form_up.FormUploader(config);
  const putExtra = new qiniu.form_up.PutExtra();
  // 文件上传
  return new Promise((resolved, reject) => {
    formUploader.putFile(uploadToken, key, localFile, putExtra, function(
      respErr,
      respBody,
      respInfo
    ) {
      if (respErr) {
        reject(respErr);
      }
      if (respInfo.statusCode == 200) {
        resolved(respBody);
      } else {
        resolved(respBody);
      }
    });
  });
}

# 参考资料

本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~