A
A
Andrey Okhotnikov2018-02-14 13:12:50
MongoDB
Andrey Okhotnikov, 2018-02-14 13:12:50

How to upload and store photos on server (React+Express+Mongo)?

How to transfer a photo from React to the server with subsequent storage there?
On the client, I get the object in which this file is stored

{title: "1", description: "2", photo: File(1240), authorLink: "5a718696b9a93f333bc282df", author: "123"}

Sending an object via axios
axios
    .post("http://localhost:8000/addPost", post, { withCredentials: true 
    })

But the file does not reach the server, req.body.photo = {}
app.post("/addpost", (req, res, next) => {

const post = new Post(req.body);
    post.save(err => {
        if (err) {
        console.log(err);
        res.end();
    }
   console.log("Сохранен " + post);
   res.statusCode = 200;
   res.json(post);
   }); 
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-14
@tsepen

Use FormData to submit files:

const formData = new FormData();

formData.append('file', someFile);
axios.post('/uploadFile', formData, {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
});

On the server, use middleware to handle multipart/form-data. Suitable for you: formidable , busboy , multer or any other middleware that solves this problem.

A
Andrey Okhotnikov, 2018-02-15
@tsepen

The issue is resolved, I’ll add on my own - you can accept files on the server according to this instruction https://alligator.io/nodejs/uploading-files-multer...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question