Utilizing ExpressJS to save uploaded files using the FileReader object from the front-end

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?

Answer №1

After much trial and error, I finally cracked the code. It appears that in order to decode a base64 string, we first need to extract the data:datatype; portion using regex.

Referring to a helpful post on Stack Overflow, I implemented some additional logic in my backend which resulted in success!

function decodeBase64String(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 decodedFile = decodeBase64String(inputFile);

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

Vue component does not display FabricJS image

Currently, I am facing an issue where I want to manipulate images on a canvas using FabricJS inside a VueJS app. In the view component, there is a prop called background which I pass in and then use fabric.Image.fromURL() to load it onto the canvas. Howeve ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...

Adding a line and text as a label to a rectangle in D3: A step-by-step guide

My current bar graph displays values for A, B, and C that fluctuate slightly in the data but follow a consistent trend, all being out of 100. https://i.stack.imgur.com/V8AWQ.png I'm facing issues adding lines with text to the center of each graph. A ...

When attempting to input a value in the middle of the line, the cursor unexpectedly leaps to the end

I have successfully created a code that prevents spaces at the beginning and special characters in an input field. The code is working perfectly, but there is an issue with the cursor moving to the end when trying to type at the beginning or middle of the ...

"Guidelines for implementing a post-login redirection to the homepage in React with the latest version of react-router (v

I am facing an issue where I am unable to redirect to the Home Page when I click the "Login" button during my React studies. Despite trying all possible methods for redirects, none of them seem to work. The function that is executed when I click the "logi ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

The iPad screen displays the image in a rotated position while it remains

Recently, I developed a mini test website that enables users to upload pictures and immediately see them without navigating back to the server. It seemed quite simple at first. $('input').on('change', function () { var file = this. ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

Error: There seems to be a problem with the connection (No Response Received) preventing the post on MongoDB

While attempting to post in MongoDB using Postman, I encountered an error message stating (Couldn't get any Response), with no errors displayed in the command nodemon. Can someone please assist me in identifying where I went wrong and suggest solution ...

Hide <a> by setting its display property to none

Below is the HTML code: <td> <a class="link" href="#"> <span class="download">Link</span> </a> <a class="link" href="#"> <span class="csvdownload">Link 2</span> </a> </td> I am lo ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Obtaining the accurate offsetTop and offsetLeft values for an element following a CSS3 rotation

Is there a method to accurately determine the offsetTop and offsetLeft values of an element post-transform rotation? Are there any lesser-known element properties that could be helpful in this scenario? Attached is an image that can provide further clari ...

Ways to automatically update React.js state when localStorage changes occur

Is it possible to automatically update the data on the cart page whenever there are changes made to the myCart array in localStorage? Below is the code that I am currently using: const [cart, setCart] = React.useState([]) React.useEffect(() => { se ...

Field for user input along with a pair of interactive buttons

I created a form with one input field and two buttons - one for checking in and the other for checking out using a code. However, when I submit the form, it leads to a blank page in the php file. What could be causing this issue? UPDATE After changing fro ...

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...