Skip to content

Getting file size 0 after upload #208

@piyushdhamecha

Description

@piyushdhamecha

Hi guys,

I am facing one issue.

I have created middleware with multer and multer s3 to upload objects to aws s3

all seems working fine, objects are uploading properly, but in some of the files the size is 0

I investigated and found that if the file size is more than 5MB then it returns a 0

Middleware code uploadAwsS3.js

const path = require('path');
const multer = require('multer');
const multerS3 = require('multer-s3');
const { S3Client } = require('@aws-sdk/client-s3');

const filePath = 'newUploads';
const month = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];

// create s3 instance using S3Client
// (this is how we create s3 instance in v3)
const s3 = new S3Client({
  credentials: {
    accessKeyId: process.env.AWS_S3_KEY, // store it in .env file to keep it safe
    secretAccessKey: process.env.AWS_S3_SECRET,
  },
  region: process.env.AWS_S3_REGION, // this is the region that you select in AWS account
});

const s3Storage = multerS3({
  s3, // s3 instance
  bucket: process.env.AWS_S3_BUCKET, // change it as per your project requirement
  contentType: multerS3.AUTO_CONTENT_TYPE,
  acl: 'public-read', // storage access type
  metadata: (req, file, cb) => {
    cb(null, { fieldname: file.fieldname });
  },
  key: (req, file, cb) => {
    const d = new Date();
    const current_month = month[d.getMonth()];
    const currentFolder = current_month.concat(new Date().getFullYear().toString());

    const filename = path.parse(file.originalname).name;
    const model = filename.split('_').slice(-2, -1)[0];
    const dir = `${filePath}/${model}/${currentFolder}`;
    const orgFileParse = path.parse(file.originalname);

    const fileName = `${dir}/${orgFileParse.name}_${Date.now()}${orgFileParse.ext}`;

    cb(null, fileName);
  },
});

// function to sanitize files and send error for unsupported files
const sanitizeFile = (file, cb) => {
  // Define the allowed extension
  const fileExts = ['.png', '.jpg', '.jpeg', '.gif', '.zip', '.mp4'];

  // Check allowed extensions
  const isAllowedExt = fileExts.includes(
    path.extname(file.originalname.toLowerCase()),
  );

  if (isAllowedExt) {
    return cb(null, true); // no errors
  }
  // pass error msg to callback, which can be displaye in frontend
  return cb('Error: File type not allowed!');
};

// our middleware
const uploadImage = multer({
  storage: s3Storage,
  fileFilter: (req, file, callback) => {
    sanitizeFile(file, callback);
  }
});

module.exports = uploadImage;

Router

router.post('/', uploadAwsS3.array('files'), DocumentUploadController.create);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions