This commit is contained in:
dengtongyu committed 2020-11-25 16:20:11 +08:00
1 parent fe2ad7289f
commit 4804a2031b
7 files changed
+149 -2

No files matched your search

+49
View File
@@ -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;
+1
View File
@@ -9,4 +9,5 @@ module.exports = app => {
require('./router/music')(app);
require('./router/nsfw')(app);
require('./router/files')(app);
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
module.exports = app => {
const { router, controller } = app;
router.post('/files/upload', controller.files.upload);
};
+46
View File
@@ -0,0 +1,46 @@
'use strict';
// 随机长度字符串
const randomString = len => {
len = len || 10;
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const maxPos = chars.length;
let str = '';
for (let i = 0; i < len; i++) {
str += chars.charAt(Math.floor(Math.random() * maxPos));
}
return str;
};
const getSuffix = fileName => {
const arr = fileName.split('.');
let suffix = '';
if (arr.length >= 2) {
suffix = arr[arr.length - 1];
}
if (suffix) suffix = `.${suffix}`;
return suffix;
};
const getFilePath = type => {
const now = new Date();
const fullYears = now.getFullYear();
const Month = now.getMonth();
let typeStr = '';
switch (type) {
case 'blog':
typeStr = 'blog';
break;
default:
typeStr = 'media';
break;
}
const path = `${typeStr}/${fullYears}/${Month}/`;
return path;
};
module.exports = {
randomString,
getSuffix,
getFilePath,
};