zs 1 年之前
父節點
當前提交
bbc9de07f7
共有 2 個文件被更改,包括 16 次插入7 次删除
  1. 7 1
      src/controller/file.controller.ts
  2. 9 6
      src/service/file.service.ts

+ 7 - 1
src/controller/file.controller.ts

@@ -1,13 +1,19 @@
 import { Controller, Inject, Post, Files, Fields } from '@midwayjs/core';
 import { FileService } from '../service/file.service';
+import { Context } from '@midwayjs/koa';
+
 @Controller('/api')
 export class FileController {
   @Inject()
   service: FileService;
 
+  @Inject()
+  ctx: Context;
+
   @Post('/upload')
   async upload(@Files() files, @Fields() fields) {
-    const result = await this.service.upload(files, fields);
+    const route = this.ctx.query.route;
+    const result = await this.service.upload(files, fields, route);
     return result;
   }
 }

+ 9 - 6
src/service/file.service.ts

@@ -11,11 +11,8 @@ export class FileService {
   @Config('export.root_path')
   root_path;
 
-  @Config('export.file_type')
-  file_type;
-
-  async upload(files, fields) {
-    const path = `${this.root_path}${sep}${this.file_type}`;
+  async upload(files, fields, route) {
+    const path = `${this.root_path}${sep}${route}`;
     if (!path) {
       throw new ServiceError(
         '服务端没有设置存储路径',
@@ -34,10 +31,16 @@ export class FileService {
       await sharp(val.data)
         .toFormat('jpg', { mozjpeg: true })
         .toFile(`${filePath}${filename}.jpg`);
+      const dirs = [];
+      if (route && route !== '_') {
+        const subs = route.split('_');
+        dirs.push(...subs);
+      }
+      const uri = `/files/${dirs.join('/')}/${filename}.jpg`;
       return {
         id: filename,
         name: `${filename}.jpg`,
-        uri: `/files/${path}/${filename}.jpg`,
+        uri,
       };
     }
   }