You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多文件上传时如何返回对象数组?是否需新建服务?

问题解答

1. 实现响应返回对象数组的方案

你当前使用的FileInterceptor仅支持处理单个文件上传,要实现多文件上传并返回对象数组,需要做以下调整:

控制器修改

将FileInterceptor替换为FilesInterceptor(用于处理多个同名上传文件),示例代码如下:

@Post('upload')
// 第二个参数为允许上传的最大文件数量,可根据需求调整
@UseInterceptors(FilesInterceptor('file', 10))
async uploadFiles(
  @UploadedFiles() files: Express.Multer.File[], 
  @Req() request: Request
) {
  // 遍历所有上传文件,批量创建文件记录
  const fileRecords = await Promise.all(
    files.map(file => this.fileService.create({
      name: file.originalname,
      path: file.originalname,
      type: file.originalname.split('.').pop(),
      size: file.size,
      user: request.user.user_id,
      parent: request.body.parent || undefined,
    }))
  );

  return fileRecords; // 返回文件记录数组
}

服务层优化(可选)

如果你的ORM支持批量插入,可以修改服务的create方法,让它同时支持单个和批量数据的处理,保证接口返回格式统一:

async create(data: any | any[]): Promise<any[]> {
  if (Array.isArray(data)) {
    return this.repository.save(data); // 批量插入
  }
  return [await this.repository.save(data)]; // 单个数据也返回数组
}

2. 是否需要创建新服务?

不需要。现有fileService已经具备创建文件记录的核心能力,只需扩展它的逻辑以支持批量操作即可,完全没必要新建服务。

内容的提问来源于stack exchange,提问作者Nonsense

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:01:35