koa实现七牛上传
【摘要】 记录如何用 koa 实现七牛上传 安装依赖busboyqiniu 实现详解引入必要的模块const Koa = require('koa');const app = new Koa();const Router = require('koa-router');const router = new Router();const path = require('path');const fs =...
记录如何用 koa 实现七牛上传
安装依赖
- busboy
- qiniu
实现详解
- 引入必要的模块
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');
- 添加上传请求路由处理
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();
});
- 将接受到的文件存至本地
// 上传到本地服务器
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;
};
- 上传至七牛存储桶
// 上传到七牛
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);
}
});
});
}
参考资料
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)