将调整大小的照片上传到 S3 存储桶

时间:2021-07-27 12:16:13

标签: javascript typescript amazon-s3 backend nestjs

我是 Nestjs 框架的初学者,特别是打字稿。我正在研究类似 Gumtree 或 Wallapop 的东西。目前我正在将照片上传到 S3 存储桶,我的任务是上传缩略图。上传简单的照片工作正常,但我想再次上传我从前端获得的照片 ID 数组的第一张照片。前端发布单张照片,服务器向 S3 存储桶发送单个请求,服务器将创建的 ID 和 URL 发送回前端。提交接受整个广告的请求后,我得到了照片 ID 以保存在数据库中。我想获取照片数组的第一个 ID,下载并再次发送改变照片大小的 trought multer。我不知道如何再次将照片传递给multer。我想强调的是,我使用了 https://medium.com/@shamnad.p.s/image-upload-to-aws-s3-using-nestjs-and-typescript-b32c079963e1 中的代码,但我不了解所有代码的工作原理。有没有其他方法可以做到这一点?也许我的方法是错误的。

一些片段:

服务:

@Injectable()
export class FileUploadService {
  constructor(
    @InjectRepository(Photos)
    private readonly uploadRepository: Repository<Photos>,
    private readonly timerJobsService: TimerJobsService,
  ) {}

  async uploadSingle(@Req() req, @Res() res) {
    try {
      await this.upload(req, res, async (error) => {
        if (error) {
          if (error.code === 'LIMIT_FILE_SIZE') {
            return res
              .status(400)
              .json(`Failed to upload image file: ${error}. Max size is 2mb`);
          } else {
            return res
              .status(400)
              .json(`Failed to upload image file: ${error}`);
          }
        }

        const photo = new Photos();
        photo.url = req.files[0].location;
        photo.key = req.files[0].key;
        photo.to_archived = true;
        await this.uploadRepository.save(photo);
        this.timerJobsService.addTimeout(
          photo.id,
          photo.key,
          1000 * 60 * 60 * 24,
        );
        res.status(200).json({
          id: photo.id,
          url: photo.url,
        });
      });
    } catch (error) {
      console.log(error);
      return res.status(400).json(`Failed to upload image file: ${error}`);
    }
  }

  async uploadSingleThumbnail(@Req() req, @Res() res) {
    try {
      await this.uploadThumbnail(req, res, async () => {
        const photo = new Photos();
        photo.url = req.files[0].location;
        photo.key = req.files[0].key;
        photo.to_archived = false;
        await this.uploadRepository.save(photo);
        res.status(200).json({
          id: photo.id,
          url: photo.url,
        });
      });
    } catch (error) {
      console.log(error);
      return res.status(400).json(`Failed to upload image file: ${error}`);
    }
  }

  async downloadSingle(key: string) {
    try {
      const properties = await s3
        .getObject({
          Bucket: AWS_S3_BUCKET_NAME,
          Key: key,
        })
        .createReadStream();
      const writeStream = fs.createWriteStream(
        path.join(
          '[path]',
          key,
        ),
      );
      properties.pipe(writeStream);
    } catch (e) {
      console.log(e);
    }
  }

  upload = multer({
    storage: multerS3({
      s3: s3,
      bucket: AWS_S3_BUCKET_NAME,
      acl: 'public-read',
      key: function (request, file, cb) {
        const file1 = file.originalname;
        if (!file1.match(/\.(jpg|png|jpeg)$/)) {
          cb('Wrong file format. Only _.png _.jpg _.jpeg format', true);
        } else {
          cb(null, `${uuid()}-${file.originalname}`);
        }
      },
    }),
    limits: { fileSize: 2097152 },
  }).any();

  uploadThumbnail = multer({
    storage: multerS3({
      s3: s3,
      bucket: AWS_S3_BUCKET_NAME,
      acl: 'public-read',
      key: function (_, file, cb) {
        cb(null, `${uuid()}-${file.originalname}-thumbnail`);
      },
      resize: {
        width: 200,
        height: 150,
      },
    }),
  }).any();
}

控制器:

  @Post()
  @ApiOperation({ description: 'Upload photo' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  async create(@Req() request, @Res() response) {
    try {
      await this.fileUploadService.uploadSingle(request, response);
    } catch (error) {
      return response
        .status(400)
        .json(`Failed to upload file: ${error.message}`);
    }
  }

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async createThumbnail(@UploadedFile() file, @Res() response) {
    try {
      await this.fileUploadService.uploadSingleThumbnail(file, response);
    } catch (e) {
      return response
        .status(400)
        .json(`Failed to upload thumbnail: ${e.message}`);
    }
  }

0 个答案:

没有答案