Transform video and image with multer-s3-transform

525 Views Asked by At

I'm trying to upload media to S3 with multer-s3-transform Here is my endpoint:

router.post(
    ROUTE_CONSTANT.PRODUCT_IMAGES,
    validation.verifyProductExisted,
    uploadImage.single('image'),
    uploadProductImage
  );

Here is my multer-s3-transform implementation:

  const uploadImage = multer({
  fileFilter: imageTypeFilter,
  limits: {
    fileSize: configEnv.mediaFileSizeLimit * 1024 * 1024,
  },
  storage: multerS3({
    s3,
    bucket: configEnv.productMediaBucket,
    acl: 'public-read',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    shouldTransform(
      req: Request,
      file: Express.Multer.File,
      cb: (arg0: any, arg1: boolean) => void
    ) {
      cb(null, true);
    },
    transforms: [
      {
        id: 'original',
        key(
          req: Request,
          file: Express.Multer.File,
          cb: (arg0: any, arg1: string) => void
        ) {
          const fileName = `${req.params.id}-${new Date().getTime()}`;
          if (imageMimeType.includes(file.mimetype)) {
            cb(null, `images/${fileName}.jpg`);
          } else {
            cb(null, `videos/${fileName}.mp4`);
          }
        },
        transform(req: Request, file: Express.Multer.File, cb: any) {
          if (imageMimeType.includes(file.mimetype)) {
            cb(null, sharp().jpeg());
          } else {
            cb(
              null,
              ffmpeg()
                .videoCodec('libx264')
                .audioCodec('aac')
                .outputFormat('mp4')
                .outputOptions(['-movflags frag_keyframe+empty_moov'])
            );
          }
        },
      },
    ],
  }),
});

The image's part is working fine with Sharp, now I want to use fluent-ffmpeg to transform the video as well. I still can not figure out how to make the ffmpeg return a ReadableStream or Buffer so that it can be uploaded to S3 due to this code of multer-s3-transform:

  storage.getTransforms[i].transform(req, file, function (err, piper) {
  if (err) return cb(err);
  
  var upload = storage.s3.upload({
    Bucket: opts.bucket,
    Key: key,
    ACL: opts.acl,
    CacheControl: opts.cacheControl,
    ContentType: opts.contentType,
    Metadata: opts.metadata,
    StorageClass: opts.storageClass,
    ServerSideEncryption: opts.serverSideEncryption,
    SSEKMSKeyId: opts.sseKmsKeyId,
    Body: (opts.replacementStream || file.stream).pipe(piper),
  });

Many thanks

0

There are 0 best solutions below