简体   繁体   中英

ExpressJS - how to writeFile passed from the front-end file upload FileReader

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?

Finally figured it out. It turns out before decoding as base64 string, the data:datatype; part needs to be extracted out of that string using regex.

Based on this post , I added some more logic to my backend and it now works!

function decodedBase64File(dataString) {
    var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
      response = {};
  
    if (matches.length !== 3) {
      return new Error('Invalid input string');
    }
  
    response.type = matches[1];
    response.data = Buffer.from(matches[2], 'base64');
  
    return response;
  }
  

  var decodedResumeFile = decodedBase64File(resumeFile);

fs.writeFile(resume,decodedResumeFile.data, (err) => {
    if (err) throw err;
    console.log('The file has been saved!')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM