4

koa实现七牛上传

 3 years ago
source link: http://xuedingmiao.com/blog/koa_qiniu_upload.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

记录如何用 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);
      }
    });
  });
}

# 参考资料


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK