William Knight William Knight - 1 month ago 37
Node.js Question

Using Multer to upload a file and briefly store it in memory before parsing and uploading to database

I'm relatively new to programming but I'll try to make this as concise as possible.

I'm using multer to try to upload an XML file. I have a Node Express server and am using React with .jsx as well. After uploading I'll be parsing that file data and posting that to a Postgres database. So with that in mind I'm not writing the uploaded file to disk, I'm just storing it in memory using multer's buffer property before parsing.

I got multer working in a small test project using jQuery for form submission but I'm not using jQuery here and I'm not sure how form submission really works in React, or if that's even the issue. I'm only including the code that directly relates to using multer. Everything else is working fine.

Here's my form:

<form
id="uploadForm"
ref="form"
encType="multipart/form-data"
method="post"
action="/upload"
onSubmit={this.handleSubmit}
>
<input
type="file"
name="songlist"
/>
<input
type="submit"
value="UploadFile"
name="submit"
/>
</form>


Here's my form submission handling in the same component. Does onSubmit automatically submit the form or am I supposed to be doing something else here?

handleSubmit(event) {
console.log('hey');
event.preventDefault();
this.props.postSongs();
},


postSongs() makes a call to my server-side routing:

postSongs() {
axios.post("/upload")
.then(() => {
console.log('success')
})
.catch((err) => {
console.error(err);
});
},


And here in my server-side route I'm making the post request which should get that file stored in multer's memory:

const multer = require('multer');
const upload = multer({inMemory: true});

router.post('/upload', upload.single('songlist'), (req, res, next) => {

console.log(req.file);

knex('songs')
.where('admin_id', adminId)
.first()
.then((songs) => {
console.log(songs);
})
.catch((err) => {
next(err);
});
});


I know there's missing pieces in this code in regards to achieving my final goal but right now I'm just trying to log multer's file object (req.file). I thought that
upload.single('songlist')
was supposed to access the particular input named songlist in the form, and my post that matches the form's action was supposed to match all that up?

I dont think I'm explaining this properly. Any help? I've wasted so much time on this.

Answer

You're not posting the form, you're posting an empty body. Try this instead:

var formData = new FormData(document.getElementById('uploadForm'));
axios.post('upload', formData)
  .then(() => {
    console.log('success');
  })
  .catch((err) => {
    console.error(err);
  });
Comments