Despite researching multiple posts on this topic, I am still unable to successfully upload a file after numerous adjustments.
My React form includes a PDF file upload component which looks 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 have attempted to decode and save this file.
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!')
})
}
However, the resulting saved file is corrupted and unable to open. It seems that either my encoding or decoding process is incorrect. I have experimented with various methods such as using btoa()
for encoding on the frontend and manual decoding on the backend, attempting to use Buffer, and more. What could be the missing piece in this puzzle?