Doniyor Otamurodov
Doniyor Otamurodov

Reputation: 121

How can I upload file from React to Express server?

I have some troubleshoot with uploading files from react to server side, can you please show me how it must be made correctly?

Bellow, I'm trying to explain the idea what I'm trying to do...

Here is the frontend how looks like:

uploadFile(e) {
  let file = e.target.files[0];
  axios.post("/uploadFileAPI", file);
}
<input type="file" onChange={this.uploadFile()} />

Here is the backend:

router.post("/uploadFileAPI", (req, res) => {
  console.log(req.body.file); //Just need to console log fetched files here or it's path maybe
});

I hope you get point, what I'm trying to do. Can you please show me an example how it should be implemented properly? Thank you

Upvotes: 5

Views: 12115

Answers (2)

Sayooj V R
Sayooj V R

Reputation: 2363

make the following chages.

<input type="file" onChange={this.uploadFile} />

import axios from 'axios';
uploadFile(event){
  const data = new FormData() ;
  data.append('file', event.target.files[0]);
  axios.post("${apiUrl}/uploadFileAPI", data)
      .then(res => { // then print response status
        console.log(res.statusText)
      })
}

api side

const multer = require('multer');
const storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, 'uploads')
    },
    filename: (req, file, callBack) => {
        callBack(null, `${file.originalname}`)
    }
  })
let upload = multer({ dest: 'uploads/' })
const server = express();
server.post('/uploadFileAPI', upload.single('file'), (req, res, next) => {
    const file = req.file;
    console.log(file.filename);
    if (!file) {
      const error = new Error('No File')
      error.httpStatusCode = 400
      return next(error)
    }
      res.send(file);
  })

to learn about this refer https://www.youtube.com/watch?v=-Hvmj8yXfyU

Upvotes: 7

gdh
gdh

Reputation: 13692

you are calling the function in the onChange. You need to pass the function reference instead.

<input type="file" onChange={this.uploadFile} /> // remove the parenthesis i.e. ()

EDIT based on comment:

For receiving file at the backend, you can use libraries like multer or express-fileupload . Multer is a popular choice. There are lot of resources available online which helps you both from a frontend and backend perspective. See these for ex:

Upvotes: 3

Related Questions