Skip to content

A super simple Multer question, nested file uploading #773

@Mertakus

Description

@Mertakus

I'm trying to do an image upload with Multer and Express. Doing just an image upload is going fine and everything works, the problem is, I want to send more than just one photo. Let me explain. I got the most basic form ever, not worth sharing. Then when submitting the form with JUST an image, the axios request looks like this:

`async onSubmit() {
const formData = new FormData();
formData.append('file', this.person.personData.file)
this.obj.file = formData

try {
    await axios.post('/projects/new', this.obj.file);
    this.message = 'Uploaded';
} catch (err) {
    console.log(err);
    this.message = 'Something went wrong'
}

},`

The post route in Express to receive the image looks like this:

`personRoutes.post('/new', upload.single('file'), (req, res) => {
console.log('BODY: ', req.body)
console.log('REQ.FILE: ', req.file)

const person = new Person({
    personData: {
        file: req.file.path
    }
});
person.save()
    .then(result => {
        console.log('YES', result)
        res.redirect('/projects')
    })
    .catch(err => {
        console.log('KUT', err)
    })

});`

Req.file is the upload.single('file') file. Req.body will hold the text fields, if there were any. Ez Pz, so far so good. Now, where things get a bit sketchy is, what if I wanted to upload more than just one photo? So my obj object would not only hold a file property but a few others aswell. Currently I am directly sending the formData file with:

await axios.post('/projects/new', this.obj.file);

But if my obj contained more than just a file, I would have to to this:

await axios.post('/projects/new', this.obj);

But what in the world should my Express post route look like? Because req.file will now (as far as I know) forever be undefined because file is not defined inside req object. It is defined in req.body object. Accessing the file as req.obj.file won't do anything. Any help would be very much appreciated. I don't even know if it is possible. And if not, what other options do I have?

Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions