I am working on a react component where I want to upload a excel file to a server. Here is what I am trying. But it gives me an empty object when I console request body
<input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/> Here is file handler method which will execute when input file changed:
fileHandler = (event) => { event.preventDefault(); let fileObj = event.target.files[0]; console.log(fileObj); //console.log(JSON.stringify(fileObj)); var data = new FormData() data.append('file', fileObj) fetch("/upload", { method: 'POST', body: data }).then(function(response) { if (response.status >= 400) { throw new Error("Bad response from server"); } return response.text(); }).then(function(data) { console.log(data) }).catch(function(err) { console.log(err) }); } Here is the server code to upload a file.
app.post('/upload', function(req, res) { console.log(req.body); // Output : {} or undefined /*try { if(!req.files) { res.send({ status: false, message: 'No file uploaded' }); } else { let avatar = req.files.avatar; //Use the mv() method to place the file in upload directory (i.e. "uploads") avatar.mv('./uploads/' + avatar.name); //send response res.send({ status: true, message: 'File is uploaded', data: { name: avatar.name, mimetype: avatar.mimetype, size: avatar.size } }); } } catch (err) { res.status(500).send(err); }*/ }) If I try below using form action it is giving me correct output in req.files but I don't want to redirect.
<form id="myForm" method="post" encType="multipart/form-data" action="/upload"> <input type="hidden" name="msgtype" value="2"/> <input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/> <input type="submit" value="Upload" /> </form> Also I don't want to use axios as I am using the same fetch request for all other execution. Any help is appreciated.
"Upload file using fetch()"?