更新
This commit is contained in:
1 parent
fe2ad7289f
commit
4804a2031b
7 files changed
+149
-2
No files matched your search
@@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
const Controller = require('egg').Controller;
|
||||
const fs = require('fs');
|
||||
const { COPYFILE_EXCL } = fs.constants;
|
||||
const respFormat = require('../util/respFormat');
|
||||
const { randomString, getSuffix, getFilePath } = require('../util/tool');
|
||||
|
||||
class FilesController extends Controller {
|
||||
async upload() {
|
||||
const { ctx } = this;
|
||||
console.log(ctx.request.body);
|
||||
console.log('got %d files', ctx.request.files.length);
|
||||
|
||||
try {
|
||||
|
||||
const filesResult = [];
|
||||
const rootPath = this.config.uploadBasePath;
|
||||
// 遍历处理多个文件
|
||||
for (const file of ctx.request.files) {
|
||||
console.log('field: ' + file.fieldname);
|
||||
console.log('filename: ' + file.filename);
|
||||
console.log('encoding: ' + file.encoding);
|
||||
console.log('mime: ' + file.mime);
|
||||
console.log('tmp filepath: ' + file.filepath);
|
||||
const type = ctx.request.body.type;
|
||||
const suff = getSuffix(file.filename);
|
||||
const newFileName = randomString(16) + suff;
|
||||
const filePath = rootPath + getFilePath(type);
|
||||
if (!fs.existsSync()) fs.mkdirSync(filePath);
|
||||
const targetPath = filePath + newFileName;
|
||||
await fs.copyFileSync(file.filepath, targetPath, COPYFILE_EXCL);
|
||||
const item = {
|
||||
filename: file.filename,
|
||||
url: `https://image.dengtongyu.com${targetPath}`,
|
||||
};
|
||||
filesResult.push(item);
|
||||
}
|
||||
|
||||
ctx.body = respFormat({ data: filesResult });
|
||||
await ctx.cleanupRequestFiles();
|
||||
} finally {
|
||||
// 需要删除临时文件
|
||||
await ctx.cleanupRequestFiles();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FilesController;
|
||||
Reference in new issue
Block a user