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/music')(app);
require('./router/nsfw')(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,
};
+23
View File
@@ -0,0 +1,23 @@
/* eslint valid-jsdoc: "off" */
'use strict';
const path = require('path');
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
// eslint-disable-next-line no-unused-vars
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
config.uploadBasePath = path.join(__dirname, '../');
return {
...config,
};
};
+21
View File
@@ -0,0 +1,21 @@
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
// eslint-disable-next-line no-unused-vars
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
config.uploadBasePath = '/webroot/image/';
return {
...config,
};
};
+2 -2
View File
@@ -27,9 +27,9 @@
"node": ">=10.0.0" "node": ">=10.0.0"
}, },
"scripts": { "scripts": {
"start": "egg-scripts start --daemon --title=egg-server-api-service", "start": "EGG_SERVER_ENV=prod egg-scripts start --daemon --title=egg-server-api-service",
"stop": "egg-scripts stop --title=egg-server-api-service", "stop": "egg-scripts stop --title=egg-server-api-service",
"dev": "egg-bin dev", "dev": "EGG_SERVER_ENV=local egg-bin dev",
"debug": "egg-bin debug", "debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local", "test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test", "test-local": "egg-bin test",