1

I'm trying to use Multer-S3, and it works like a charm to upload images.

My challenge is that before running the Multer-S3 middleware, I want to have some kind of control flow, where it's possible to check if the req.body contains numbers for some fields, if the file is of a specific type etc before the Multer-S3 middleware runs.

As I'm using form-data, I need to use multer or similar to get access to the req.body and the req.file, but if I use another middleware with multer, it no longer works.

Anyone got ideas how to do this?

Below sample code to try to explain:

const express = require('express'); //"^4.13.4"
const aws = require('aws-sdk'); //"^2.2.41"
const bodyParser = require('body-parser');
const multer = require('multer'); // "^1.3.0"
const multerS3 = require('multer-s3'); //"^2.7.0"

aws.config.update({
    secretAccessKey: 'YOUR_ACCESS_SECRET_KEY',
    accessKeyId: 'YOUR_ACCESS_KEY_ID',
    region: 'us-east-1'
});

const app = express();
const s3 = new aws.S3();

app.use(bodyParser.json());

const upload = multer({
    storage: multerS3({
        s3: s3,
        acl: 'public-read',
        bucket: 'YOUR_BUCKET_NAME',
        key: function (req, file, cb) {
            console.log(file);
            cb(null, file.originalname); //use Date.now() for unique file keys
        }
    })
});

//This is where I would like to add some controll flow to check the req.body and req.file
// before the middleware upload is used.
//When using another multer middleware before to get access to the req body and file,
//it seems I can't use the upload middleware to upload..
app.post('/upload', upload.single("file"), (req, res, next) => {
    res.send("Uploaded!");
});


app.listen(3000, () => {
    console.log('Example app listening on port 3000!');
});

Anyone able to help?

Best regards, Oscar

Oscar Ekstrand
  • 581
  • 1
  • 4
  • 13
  • do you want to check only file's extension type or any other condition will be there? – turivishal Mar 17 '21 at 08:48
  • Hi, I wish to also check some req.body properties (if req.body.price is a number etc). Also preferably file size and extension. Do you have any ideas? – Oscar Ekstrand Mar 17 '21 at 09:51
  • I don't think its possible in form-data with image multipart, you can access headers before image upload so pass price field in headers and check your conditions, second if you want to check image extension then use `fileFilter` propertie of `multer` function and check file extension condition. – turivishal Mar 17 '21 at 11:07

1 Answers1

0

This works for me:

let formData = new FormData()
formData.append('param', this.data)
formData.append('dataForFile', this.$refs.file.files[0])
this.$axios.post(`/file/upload`, formData)
  .then(data => {
    ...
  })

It's important to remember that you place the file data last in the formData list.

Wayne Smallman
  • 1,690
  • 11
  • 34
  • 56