DEV Community

Brett Connolly
Brett Connolly

Posted on

Process FormData file sent to Node server

I struggled to find much online about how to simply process a FormData file (PDF, in this case) sent to a Node server to be attached to an email or used for other things. This is a very basic example but the key part is this line on the server:

Buffer.from(await file.arrayBuffer())

form.html

<form id="fileForm">
  <div>
    <label for="pdf_file">File Upload</label>
      <input type="file" name="pdf_file" />
  </div>
  <button type="submit">Send File</button>
</form>
Enter fullscreen mode Exit fullscreen mode

form.js

document.getElementById("fileForm").addEventListener("submit", (e) => {
  e.preventDefault();
  const formData = new FormData(e);
  fetch("/", {
    method: "POST",
    body: formData
  });
});
Enter fullscreen mode Exit fullscreen mode

server.js

app.post('/', async (request, response) => {
  const values = await request.formData();
  const file = values.get("pdf_file");
  const processedFile = Buffer.from(await file.arrayBuffer());
  //attach to email or do other things
};
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more