File.controller.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Context } from '@midwayjs/koa';
  2. import { join, sep } from 'path';
  3. import { FileService } from '../service/File.service';
  4. import { createReadStream } from 'fs';
  5. import { Controller, Inject, Config, Post, Files, Fields, Get } from '@midwayjs/core';
  6. import * as mime from 'mime-types';
  7. /**文件上传默认类 */
  8. @Controller('/files', { ignoreGlobalPrefix: true })
  9. export class FileController {
  10. @Inject()
  11. ctx: Context;
  12. @Inject()
  13. fileService: FileService;
  14. @Config('upload.realdir')
  15. uploadDir;
  16. /**
  17. * 文件上传
  18. * @param {Array} files 文件数组
  19. * @param {object} fields 其他字段
  20. * @param {string} project 项目名
  21. * @param {string} catalog 文件层级名 用'_'连接上下层级
  22. * @param {string} item 文件名,没有默认用时间戳
  23. */
  24. @Post('/:project/upload')
  25. @Post('/:project/:catalog/upload')
  26. @Post('/:project/:catalog/:item/upload')
  27. async upload(@Files() files, @Fields() fields) {
  28. const { project, catalog, item } = this.ctx.params;
  29. const dirs = [project];
  30. if (catalog && catalog !== '_') {
  31. const subs = catalog.split('_');
  32. dirs.push(...subs);
  33. }
  34. let path = this.uploadDir;
  35. // 检查分级目录是否存在,不存在则创建
  36. for (let i = 0; i < dirs.length; i++) {
  37. const p = `${path}${sep}${dirs.slice(0, i + 1).join(sep)}`;
  38. this.fileService.mkdir(p);
  39. }
  40. path = `${join(path, dirs.join(sep))}${sep}`;
  41. const file = files[0];
  42. const ext = this.fileService.getExt(file.filename);
  43. let filename = `${this.fileService.getNowDateTime()}${ext}`;
  44. if (item) filename = item;
  45. const uri = `/files/${dirs.join('/')}/${filename}`;
  46. this.fileService.moveFile(file.data, `${path}${filename}`);
  47. return { id: filename, name: filename, uri, errcode: 0 };
  48. }
  49. /**
  50. * 读取文件
  51. */
  52. @Get('/*')
  53. async readFile() {
  54. const shortRealPath = this.fileService.getFileShortRealPath();
  55. const realPath = join(this.uploadDir, shortRealPath);
  56. this.ctx.body = createReadStream(realPath);
  57. const type = mime.lookup(realPath);
  58. this.ctx.response.set('content-type', type);
  59. }
  60. @Post('/clear/files')
  61. async clearFiles() {
  62. try {
  63. // 先重写文件地址表
  64. const modelResults = this.fileService.scanModelHaveFile();
  65. await this.fileService.setFileUriFromDefaultDataBase(modelResults);
  66. // 再清除未使用的上传文件
  67. await this.fileService.deleteNoUseFile();
  68. } catch (error) {
  69. console.error(error);
  70. }
  71. return 'ok';
  72. }
  73. }