nest.js fileInterceptor等待文件移动

发布于 2025-02-12 14:31:37 字数 837 浏览 0 评论 0原文

我在上传后立即获取图像有问题。这是我的后端代码,这是有效的:

@Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: join(__dirname, '../../../', 'static/files'),
        filename: async (req, file, callback) => {
          const fileExtName = extname(file.originalname);
          const randomName = await randomUUID();
          await callback(null, `${randomName}${fileExtName}`);
        },
      }),
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
  ): Promise<DataResponseDto<UploadedFileDto>> {
    const url = `${this.configService.apiConfig.apiStaticUrl}/${file.filename}`;
    return { data: { uploadedFileUrl: url } };
  }

问题是,当我在上传后立即获取图像时,我会收到HTTP错误503。这意味着该文件在获取之前尚未移至静态文件夹。

在返回图像URL之前,我该如何等待它在控制器中移动?

I have a problem with fetching the image right after upload. Here's my back-end code, that's working:

@Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: join(__dirname, '../../../', 'static/files'),
        filename: async (req, file, callback) => {
          const fileExtName = extname(file.originalname);
          const randomName = await randomUUID();
          await callback(null, `${randomName}${fileExtName}`);
        },
      }),
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
  ): Promise<DataResponseDto<UploadedFileDto>> {
    const url = `${this.configService.apiConfig.apiStaticUrl}/${file.filename}`;
    return { data: { uploadedFileUrl: url } };
  }

The problem is that when I fetch the image right after upload, I get an HTTP error 503. Meaning the file hasn't been moved to the static folder before being fetched.

How can I wait for it to be moved in the controller, before returning the image URL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文