0

I'm trying to send a form that contains an image or a set of images to an Express API, using Axios. When I try to send it, i get the following error on Express:

MulterError: Unexpected field

I am using React-Dropzone to get the files. After that I'm getting all of the form data through state and then transforming the object into FormData(). I have tried with and without the following config on axios: {headers: {'Content-Type': 'multipart/form-data'} } But the result is always the same.

My express route:

app.post('/adverts', requireAuth, upload.array('images'), Adverts.create);

My multer config (using multer-s3):

const multer = require('multer');
const multerS3 = require('multer-s3');
const uuid = require('uuid/v1');
const aws = require('aws-sdk');

const s3 = new aws.S3({
    accessKey: process.env.AWS_ACCESS_KEY,
    secretAccesKey: process.env.AWS_SECRET,
    region: 'eu-west-1',
});

const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: process.env.AWS_S3_IMG,
        acl: 'public-read',
        metadata: function(req, file, cb) {
            cb(null, { fieldName: file.fieldname });
        },
        key: function(req, file, cb) {
            cb(null, `${req.user.id}/${uuid()}`);
        },
    }),
});
module.exports = upload;

My react component:

<form onSubmit={this.handleSubmit.bind(this)} encType="multipart/form-data">
    <TextField
        fullWidth
        label='title'
        value={this.state.title}
        onChange={e => this.setField('title', e)}
        type="text"
        required
        />
    <Dropzone onDrop={this.onDrop} accept=".png,.jpg,.jpeg" maxSize={5000000} name="images">
        {({ getRootProps, getInputProps, isDragActive }) => {
            return (
                <div className={classes.dropBox} {...getRootProps()}>
                    <input {...getInputProps()} />
                    {isDragActive ? <p>Drop...</p> : <p>Drag here and drop to upload</p>}
                 </div>
            );
        }}
    </Dropzone>
    <Button color="primary" variant="contained" type="submit">
        Create
    </Button>
</form>

Form handleSubmit function:

handleSubmit = e => {
     e.preventDefault();
     const { title, images } = this.state;
     /* some validation */

     const formData = objectToFormData(values);
     api.post('/adverts', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(advert =>
          Router.push(`/ad/${advert.data.reference}`)
      );
}

onDrop function, triggered when a user adds an image:

onDrop = files => {
    const images = this.state.images.concat(
        files.map(file =>
            Object.assign(file, {
                preview: URL.createObjectURL(file),
            })
        )
    );

    const totalsize = images.reduce((total, current) => {
        return total + current.size;
    }, 0);

    if (totalsize < 5000000) {
        this.setState({
            images,
            fileSize: (totalsize / 1e6).toFixed(2),
            filePercentage: (totalsize * 100) / 5000000,
        });
    }
};

1 Answer 1

0

error in your code is that you are sending single image and while accepting you are accepting array

try

app.post('/adverts', requireAuth, upload.single('image'), Adverts.create);
1
  • I have also tried that, but it doesn't seem to work. My images state is an array containing the files. I edit to add the onDrop function, triggered when a user adds an image. Feb 19, 2019 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.