|
@@ -0,0 +1,58 @@
|
|
|
+import { Inject, Controller, Post, Files, Fields, Config, Get } from '@midwayjs/decorator';
|
|
|
+import { Context } from '@midwayjs/koa';
|
|
|
+import { join, sep } from 'path';
|
|
|
+import { FileService } from '../service/file.service';
|
|
|
+import { createReadStream } from 'fs';
|
|
|
+import { getType } from 'mime';
|
|
|
+@Controller('/')
|
|
|
+export class FileController {
|
|
|
+ @Inject()
|
|
|
+ ctx: Context;
|
|
|
+ @Inject()
|
|
|
+ fileService: FileService;
|
|
|
+ @Config('koa.globalPrefix')
|
|
|
+ globalPrefix: string;
|
|
|
+
|
|
|
+ uploadDir = 'upload';
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 文件上传
|
|
|
+ * @param {Array} files 文件数组
|
|
|
+ * @param {object} fields 其他字段
|
|
|
+ * @param {string} project 项目名
|
|
|
+ * @param {string} catalog 文件层级名 用'_'连接上下层级
|
|
|
+ * @param {string} item 文件名,没有默认用时间戳
|
|
|
+ */
|
|
|
+ @Post('/api/files/:project/upload')
|
|
|
+ @Post('/api/files/:project/:catalog/upload')
|
|
|
+ @Post('/api/files/:project/:catalog/:item/upload')
|
|
|
+ async upload(@Files() files, @Fields() fields) {
|
|
|
+ const { project, catalog, item } = this.ctx.params;
|
|
|
+ const dirs = [project];
|
|
|
+ if (catalog && catalog !== '_') {
|
|
|
+ const subs = catalog.split('_');
|
|
|
+ dirs.push(...subs);
|
|
|
+ }
|
|
|
+ let path = join(process.cwd(), this.uploadDir);
|
|
|
+ // TODO: 检查分级目录是否存在,不存在则创建
|
|
|
+ for (let i = 0; i < dirs.length; i++) {
|
|
|
+ const p = `${path}${sep}${dirs.slice(0, i + 1).join(sep)}`;
|
|
|
+ this.fileService.mkdir(p);
|
|
|
+ }
|
|
|
+ path = `${join(path, dirs.join(sep))}${sep}`;
|
|
|
+ const file = files[0];
|
|
|
+ const ext = this.fileService.getExt(file.filename);
|
|
|
+ let filename = `${this.fileService.getNowDateTime()}${ext}`;
|
|
|
+ if (item) filename = item;
|
|
|
+ const uri = `${this.globalPrefix}/files/${dirs.join('/')}/${filename}`;
|
|
|
+ this.fileService.moveFile(file.data, `${path}${filename}`);
|
|
|
+ return { id: filename, name: filename, uri };
|
|
|
+ }
|
|
|
+ @Get('/files/*')
|
|
|
+ async readFile() {
|
|
|
+ const shortRealPath = this.fileService.getFileShortRealPath();
|
|
|
+ const realPath = join(process.cwd(), this.uploadDir, shortRealPath);
|
|
|
+ this.ctx.body = createReadStream(realPath);
|
|
|
+ this.ctx.response.set('content-type', `/files/${getType(realPath)}`);
|
|
|
+ }
|
|
|
+}
|