如果上传非图片文件,则出现Multer-s3-transform错误

时间:2019-07-04 04:03:38

标签: javascript node.js multer-s3

在上传到s3存储桶之前,我想将图像文件转换为较小的尺寸,因此我决定使用multer-s3-transform。我的问题是我应该能够上传非图像文件,例如pdf,docs等...,但是我一直在遇到错误。这是我的代码。

"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);

我真的认为我需要首先检查文件类型,但是我不知道该怎么做。

0 个答案:

没有答案