0

I am attempting to send an image file from my React frontend to my express API:

fetch('http://localhost:4000/upload/', {
  method: 'POST',
  body: this.state.picture[0],
})

The file looks correct in the chrome console when I log it:

File {name: "31-614x614.jpg", lastModified: 1553111550472, lastModifiedDate: Wed Mar 20 2019 12:52:30 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", size: 95101, …}

However when I try to log the file in the request on my backend, I either get undefined or empty request objects depending on how I set it up.

I've tried using multer, busboy, and express-fileupload as recommended in similar stack overflow questions, but have the same issues.

Here's my router:

const Router = require('express').Router();
const imgController = require('./controllers/imgController');

Router.get('/images/', imgController.getImages);
Router.post('/upload/', imgController.postImage);

module.exports = Router;

And the controller where I'm simply trying to see the file being sent:

exports.postImage = (req, res) => {
  console.log("IN POST IMAGE")
  console.log(req.body)
  console.log(req.files)
}

I do get into the controller, but the request never contains the file. Any help is appreciated!

1 Answer 1

1

Have you tried building a formData element and sending that?

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, just tried it, but no dice :( I believe it's something to do with my server setup being able to read the request.
You'll need to use a middleware parser to handle multipart/form-data requests: github.com/expressjs/multer
As mentioned in my post I tried both of the above packages to no avail. express-fileupload looked super simple to use too.
@David then show us your code with one of the packages
I got it working using the form data you suggested and multer, the issue was I needed to have the Router use the correct Multer middleware function, rather than the express app. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.