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

Utilizing AngularJS and Node.js to update MongoDB

Looking for a solution to update my MongoDB using Node.js and AngularJS within the front-end of my application. The code I currently have is causing an error stating `TypeError: Cannot read property 'put' of undefined. Here is my AngularJS contr ...

What is the best way to handle errors when redirecting output from a spawned command?

When I stream the stdout from a spawned command (like ffmpeg) using express, I encounter an issue where even if the child process fails, it still returns a 200 status code. Is there a way for me to send a 500 status code if the exit code is non-zero? It s ...

Understanding the Functioning of a Digital Analog Clock Using JavaScript

As a new learner, I found the operation of a Digital analog clock to be quite puzzling. I was presented with an image called clock.png, and I specifically struggled with how the hands of the clock function. Javascript - const deg = 6; // defining the valu ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

developed a regular expression to disregard .goutputstream documents

After successfully creating a watcher with chokidar, I encountered an issue when trying to ignore certain files using regex. I am struggling to figure out what went wrong in my code or regex implementation. Below is the snippet of the code: const watcher ...

iOS fixed positioning and scrolling

One of the current challenges we are facing involves implementing an action button similar to the one found in GMail for adding new content. This button needs to remain fixed during scroll. Here is the HTML code: <div class="addButton actionButton" on ...

Toastr - encountering a problem with the settings

After invoking a toastr message using the following command: Command: toastr["success"]("foo") toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-right", "prev ...

Is it possible to adjust the color of this AnchorLink as I scroll down?

Currently struggling to update the color of a logo as I scroll. While the navigation bar successfully changes colors, the logo remains stagnant. Here is the excerpt from my existing code: navigation.js return ( <Nav {...this.props} scrolled={this ...

What is the best way to choose the right value based on parameters?

I am currently working on a solution using protractor where I have several options to consider. Specifically, I need to test timeslots between 1600 and 1900, along with an else statement. For instance, if the 1600 timeslot is selected, then the code shoul ...

I'm experiencing an issue with uploading an image to Firebase as I continue to encounter an error message stating "task.on is not a function."

The console displays a message confirming a successful upload. const sendPost = () => { const id = uuid(); const storage = getStorage(); const storageRef = ref(storage, `posts/${id}`) const uploadTask = uploadString(storageRe ...

Tips and tricks for storing and retrieving form state using local storage with jQuery in JavaScript

I'm trying to save the form state in localstorage, I am able to save it successfully but I'm encountering an issue where I am unable to save the input typed data Desired outcome: If I type doggy inside the input box, I want that value to be ret ...

What is the best way to access the current webdriver instance using code?

Currently, I am in the process of creating an end-to-end test suite with Protractor. As Protractor is based on WebdriverJS, I am attempting to utilize some of its functionality. More specifically, my goal is to incorporate certain behaviors using Webdriv ...

Dynamically Inject HTML with Drag-and-Drop Interaction

Looking for an easy method to move html elements or content around on a webpage? The objective is to drag the element and release it onto a designated area. After dropping the element, customized html content will be added dynamically depending on ...

Express Session Issue Preventing Ajax Call from Functioning

After testing the /temp route directly in the browser and then through an ajax call to the /test route, I noticed a difference in the session information. When accessed directly, the session retains the data added via the /temp route, but when called throu ...

Implementing Title Attribute in Grid View Template Field

I have implemented a Grid View with a "TemplateField" that includes properties for Header Text and SortExpression set to true. Upon inspecting the browser, I noticed that it generates an anchor element with some JavaScript. How can I add a title tag to t ...

Using THREE.js in the pre-render function

I am encountering difficulties with updating the positions of my enemies before rendering them. Instead of creating a separate update() function, I attempted to use an onBeforeRender() function attached to each enemy object. However, nothing seems to be ...

Creating a personalized and versatile table component with unique functionality: where to begin?

Looking to create a versatile table component that can adapt for both desktop and mobile versions. If the screen width is below 720px, it should display a table using div, ul, li elements with a "load more" button at the bottom. If the screen width i ...

Create a JavaScript button that increases a progress bar value by 1 and adjusts its width style by 10 units

Here is the code for managing a progress bar using JavaScript: function getProgress() { return document.getElementById("progressbar").getAttribute("aria-valuenow"); } function setProgress(value) { document.getElementById("progressbar").setAttri ...

Enhancing the efficiency of a TypeScript-written file content parsing class

Seeking advice on optimizing a typescript module used by a VSCode extension. This module accepts a directory and parses the content within the files, which can be time-consuming for directories with a large number of files. To avoid copying the entire cla ...