5

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

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, but what about the backend?
You need to use multer. Updated my answer
3

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:

1 Comment

But, how can I fetch data from backend?

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.