import { Context } from '@midwayjs/koa'; import { join, sep } from 'path'; import { FileService } from '../service/File.service'; import { createReadStream } from 'fs'; import { Controller, Inject, Config, Post, Files, Fields, Get } from '@midwayjs/core'; import * as mime from 'mime-types'; /**文件上传默认类 */ @Controller('/files', { ignoreGlobalPrefix: true }) export class FileController { @Inject() ctx: Context; @Inject() fileService: FileService; @Config('upload.realdir') uploadDir; /** * 文件上传 * @param {Array} files 文件数组 * @param {object} fields 其他字段 * @param {string} project 项目名 * @param {string} catalog 文件层级名 用'_'连接上下层级 * @param {string} item 文件名,没有默认用时间戳 */ @Post('/:project/upload') @Post('/:project/:catalog/upload') @Post('/: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 = this.uploadDir; // 检查分级目录是否存在,不存在则创建 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 = `/files/${dirs.join('/')}/${filename}`; this.fileService.moveFile(file.data, `${path}${filename}`); return { id: filename, name: filename, uri, errcode: 0 }; } /** * 读取文件 */ @Get('/*') async readFile() { const shortRealPath = this.fileService.getFileShortRealPath(); const realPath = join(this.uploadDir, shortRealPath); this.ctx.body = createReadStream(realPath); const type = mime.lookup(realPath); this.ctx.response.set('content-type', type); } @Post('/clear/files') async clearFiles() { try { // 先重写文件地址表 const modelResults = this.fileService.scanModelHaveFile(); await this.fileService.setFileUriFromDefaultDataBase(modelResults); // 再清除未使用的上传文件 await this.fileService.deleteNoUseFile(); } catch (error) { console.error(error); } return 'ok'; } }