I found a many posts around this topic but after much tweaking still can't get the file upload to work correctly.
I have a form with a PDF file upload in React, something like this:
<Input
onChange={(e) => this.handleFileUpload(e)}
required
type="file"
name="resume"
id="resume"
/>
handleFileUpload = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.addEventListener("load", (upload) => {
this.setState({
resumeFile: upload.target.result,
});
});
if(file) {
reader.readAsDataURL(file)
}
}
axios.post("/api/career", {resumeFile: formData.resumeFile})
on the express server side, I tried to decode this file and save it.
const base64url = require('base64url');
router.post('/api/career', (req, res) => {
fs.writeFile('file.pdf',base64url.decode(req.body.resumeFile), (err) => {
if (err) throw err;
console.log('The file has been saved!')
})
}
But the file that gets saved is corrupted and does not open. Either I'm encoding or decoding it wrong, or something else. I tried to encode it with btoa()
on the front-end, as well as manually decode it on the back, tried using Buffer, etc. What am I missing?