这次打破常规初次使用 egg.js 框架,对于我来说也是个不小的挑战,虽然之前做过两年的前端,但是也只是切个页面写点简单的脚本而已。今天再弄后台的时候需要个上传图片的接口,捣鼓了一上午终于完成了这个上传。
// config.default.js
config.uploadBaseDir = ''; //图片保存路径
config.multipart = { // 配置上传
fileSize: '10mb',
mode: 'stream',
fileModeMatch: /^\/upload_file$/,
fileExtensions: ['.png', '.jpg', '.jpeg', '.gif'], // 扩展几种上传的文件格式
};
npm install dayjs md5-node
const path = require('path');
const md5 = require('md5-node');
const fs = require('mz/fs');
const dayjs = require('dayjs');
/**
* 上传图片至本地
* @param module
* @returns {Promise<{fileName: string, uploadPath: string, filePath: string, filePathName: string, fileBasePath: any}>}
*/
async image()
{
let stream = await this.ctx.getFileStream();
const newTime = new Date(); //当前时间
let fileBasePath = this.config.uploadBaseDir; //上传根目录
let filePath = dayjs(new Date()).format('/YYYYMMDD/'); //上传目录
let fileName = md5(newTime) + path.extname(stream.filename); //文件名
let filePathName = path.join(filePath, fileName); //文件完整路径
let uploadPath = path.join(fileBasePath, filePathName); //上传完整路径
let uploadDir = path.join(fileBasePath, filePath);
if (!fs.existsSync(uploadDir)) //判断目录是都存在,不存在创建
fs.mkdirSync(uploadDir, {recursive: true}); //recursive 参数是是否递归创建
let writerStream = fs.createWriteStream(uploadPath);
stream.pipe(writerStream);
writerStream.on('error', function(err) {
throw err.stack;
});
return {
filePath: filePath,
fileName: fileName,
filePathName: filePathName,
};
}
建站时间:2019年02月01日
文章统计:129篇文章
访问统计:1.4万次
微信公众号:扫描二维码,关注我们