egg 如何配置 文件上传?
1、 配置路由
router.post('/ppyy/upload', controller.file.upload);
2、配置 控制器
const { Controller } = require('egg');
const path = require('path');
const fs = require('fs');
class FileController extends Controller {
async upload() {
const { ctx } = this;
console.log('ctx.request');
console.log(ctx.request.files);
const file = ctx.request.files[0];
const fileinfo = fs.readFileSync(file.filepath);
const name = `ppyy_${new Date().getTime()}_${file.filename}`;
const target = path.join(this.config.baseDir, `app/public/upload/${name}`);
try {
await fs.writeFileSync(target, fileinfo);
} catch (error) {
throw error;
} finally {
await fs.unlink(file.filepath, err => {
if (err) {
throw err;
}
console.log('删除缓存文件:' + file.filepath + '成功!');
});
}
let pathId = target.slice(target.indexOf('public\\upload'));
let http = 'http://127.0.0.1:7001/';
ctx.body = { code: 200, message: '上传成功!', data: http + pathId, file };
}
}
module.exports = FileController;
3、必须配置
config.multipart = {
mode: 'file',
fileSize: '50mb',
fileExtensions: [ '.txt' ],
};
end 图片上传成功 放回一个可访问的地址