使用file模式上传文件
1,代码
controller文件:
import { Controller } from 'egg';
const path = require('path');
const fs = require('fs');
export default class HomeController extends Controller {
public async upload() {
const { ctx } = this;
const file = ctx.request.files[0];
const fileinfo = fs.readFileSync(file.filepath);
const name = `YLW_${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 + '成功!');
});
}
ctx.body = { code: 200, message: '上传成功!', data: target, file };
}
}
config.default.js:
// 启用 file 模式:
config.multipart = {
mode: 'file',
fileSize: '50mb',
fileExtensions: [ '.txt' ], // 增加对 txt 扩展名的文件支持
};