1

I want to transform image file to a much smaller size before uploading to an s3 bucket and I've decided to use multer-s3-transform. My problem is I should be able to upload non-image file as well like pdf, docs, etc... but I keep on getting an error. here is my code.

"use strict";

const config = require('../../config/config');
const _ = require('lodash');
const AWS = require('../../library/aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3-transform');
const uuid = require('../../library/uuid');
const sharp = require('sharp');

const s3 = new AWS.S3();
const multerS3Obj = multerS3({
    s3 : s3,
    bucket : config.amazon.s3.bucketName,
    acl : "public-read",
    contentType : multerS3.AUTO_CONTENT_TYPE,
    metadata : function(req, file, cb) {
        const metadataObj = Object.assign({}, req.body);

        metadataObj.content_type = file.mimetype;
        metadataObj.filename = file.originalname;

        cb(null, metadataObj);
    },
    shouldTransform : function(req, file, cb) {
        cb(null, /^image/i.test(file.mimetype));
    },
    transforms : [
        {
            key : function(req, file, cb) {
                const refType = req.params.refType,
                        refId = req.params.refId,
                        subfolder = `uploads/${refType}/${refId}/`;
                cb(null, subfolder + file.originalname);
            },
            transform : function(req, file, cb) {
                let quality = '';
                if (file.mimetype === 'image/jpeg') {
                    quality = sharp().jpeg({quality : 20});
                }
                else if (file.mimetype === 'image/png') {
                    quality = sharp().png({quality : 20});
                }
                cb(null, quality);
            }
        }
    ]
});

const multerOpt = {
    storage : multerS3Obj,
    limits : {
        fileSize : 15728640
    },
    fileFilter : (req, file, cb) => {
        cb(null, true);
    }
};

module.exports = multer(multerOpt);

I really think that I need to check the file type first but I don't know how to do it.

BPDESILVA
  • 2,040
  • 5
  • 15
  • 35
virtualninja
  • 192
  • 3
  • 16

0 Answers0