Jessica
Jessica

Reputation: 9830

How to rename a file with multer before uploading it to s3 bucket?

I want to rename every file before it gets uploaded to aws s3 bucket using multer, node.js, and express.js

This is how my current implementation looks

Font End

const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const { data } = await axios.post('api/aws/upload-image', formData);

Backend

var storage = multer.memoryStorage();
const upload = multer({ storage }).single('file');

const s3Client = new aws.S3({
    accessKeyId: config.aws.accessKey,
    secretAccessKey: config.aws.secretKey,
    region: config.aws.region
});


router.post('/upload-image', async (req, res) => {
    upload(req, res, function(err) {
        if (err instanceof multer.MulterError || err)
            return res.status(500).json(err);

        const uploadParams = {
            Bucket: config.aws.bucket,
            Key: req.file.originalname,
            ACL: 'public-read',
            Body: req.file.buffer
        };

        s3Client.upload(uploadParams, (err, data) => {
            if (err) res.status(500).json({ error: 'Error -> ' + err });

            return res.status(200).send(data.Location);
        });
    });
});

The code above works as it should. But I'm trying to rename the file before it gets uploaded.

I thought of doing this:

var storage = multer.diskStorage({
    filename: function (req, file, cb) {
      cb(null, Date.now() + '-' +file.originalname )
    }
})

But that returns a file element, not a blob element, and therefore doesn't upload to s3 bucket.

How can I make it that when file gets sent over to node.js, I first change the file name, the I upload the file?

Upvotes: 1

Views: 2195

Answers (1)

hoangdv
hoangdv

Reputation: 16157

The upload method uses PutObjectRequest, PutObjectRequest constructor the key parameter is actually the name of the uploaded file.

Just change Key value to your new name.

const uploadParams = {
  Bucket: config.aws.bucket,
  Key:  "NEW_NAME_WHAT_YOU_WANT", // req.file.originalname,
  ACL: 'public-read',
  Body: req.file.buffer
};

Upvotes: 1

Related Questions