Souradip Roy
Souradip Roy

Reputation: 300

Upload Text file from React to Node using multer

React Code for file upload:

onChangeHandler=event=>{
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    })
    console.log(event.target.files[0])
  }

  onClickHandler = () => {
    const data = new FormData() 
    data.append('file', this.state.selectedFile)
    console.log(this.state.selectedFile)
    axios.post(`${config.server}/upload`, data,{})
     .then(res => { // then print response status
         console.log(res.statusText)
  });

}
<div>
        <input type="file" name="file" onChange={this.onChangeHandler}/>
        <button type="button" class="btn btn-success btn-block" onClick={this.onClickHandler}>Upload</button>
    </div>

File Handling code of Node:

var multer=require("multer");
var cors = require('cors');

app.use(cors())
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
    cb(null, 'public')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' +file.originalname )
  }
})
var upload = multer({ storage: storage }).single('file')

app.post('/upload',function(req, res) {
    console.log(req.file) 
    upload(req, res, function (err) {
           if (err instanceof multer.MulterError) {
               return res.status(500).json(err)
           } else if (err) {
               return res.status(500).json(err)
           }
      return res.status(200).send(req.file)

    })

});

The onChangehandler is showing the file in react on console.log() but on submitting the data using the button Upload which uses the onClickHandler function. The response I get from the server is 500 and the directory with the name public where it should store the file is not getting created. What is going wrong if someone can help me. I am new to file handling in react and node. I am using the following link as reference. It is not necessary to store the file. All I need to do is process the file and read the contents inside the file. If there is some other way of doing instead of storing it. Thanks for your help.

Upvotes: 0

Views: 419

Answers (1)

Souradip Roy
Souradip Roy

Reputation: 300

The problem has been solved. I didn't have the folder public which is my destination for saving the file. There is no changes needed in the code. The destination folder needs to be present. Multer cannot create the folder if not present.

Upvotes: 1

Related Questions