Download files in Javascript from Node.js server


Download files in Javascript from Node.js server

Download files in Javascript from the Node.js server using the Express.js framework. Hi there, long time no see. In this article, I want to show you how to download files in Javascript, either you use Vue.js, React, Angular, jQuery, or Vanilla JS. On the backend side, we run on Node.js using Express.js, and I write only the route’s handler.

Back-end

import cors from 'cors';
import fs from 'fs';

.get('/download',
  cors({
    exposedHeaders: ['Content-Disposition'],
  }),
  async (req, res) => {
    try {
      const fileName = 'file.pdf'
      const fileURL = '/path/to/file/file.pdf'
      const stream = fs.createReadStream(fileURL);
      res.set({
        'Content-Disposition': `attachment; filename='${fileName}'`,
        'Content-Type': 'application/pdf',
      });
      stream.pipe(res);
    } catch (e) {
      console.error(e)
      res.status(500).end();
    }
  };
})

This code is all you need to download any file from the back-end. In this example, I used a .pdf file, but you can change the content type, on line 15.

Is very important to use CORS as middleware to determine what headers are exposedtoAxios library, on the front-end side. We need to set Content-Disposition, declared on line _1_4, to inform the client about this request which has an attachment and the filename.

Front-end

import Axios from 'axios'
const response = await Axios.get('API_URL/download', { responseType: 'blob' });
if (response.data.error) {
  console.error(response.data.error)
}

const fileURL = window.URL.createObjectURL(new Blob([response.data]));
const fileLink = document.createElement('a');
fileLink.href = fileURL;
const contentDisposition = response.headers['content-disposition'];
const fileName = contentDisposition.substring(
  contentDisposition.indexOf('filename=') + 9,
  contentDisposition.length
);
fileLink.setAttribute('download', fileName);
fileLink.setAttribute('target', '_blank');
document.body.appendChild(fileLink);
fileLink.click();
fileLink.remove();

We need to create an HTML object to be able to download the file:

<a href="" download=""></a>

Another option

Open the blob directly into browser

const response = await Axios.get('API_URL/download', { responseType: 'blob' });
const file = window.URL.createObjectURL(new Blob([response.data]));
window.open(file);

Firstly, we need to make a request to the server, for that we use Axios. As you can see the URL is API_URL, your base URL and /download API route, defined above. Need to inform Axios, that the response waited it’s of type blob, because the response is not a plain text or JSON. With that response, creates a new object and attach that content on a new a HTML tag.

I hope you enjoy the article and it was helpful. If you have any issue or wanna add some notes, please leave me in comments bellow and I’ll try to answer as fast as possible. Please hit the like button below and share this article, it helps me a lot.

Newsletter


Related Posts

A Week in the Life of an Invoice Wrangler: Navigating Ridesharing and Food Delivery Chaos

As an app founder in the ridesharing and food delivery industry, I found myself knee-deep in invoice reports from companies like Bolt, Uber, Glovo, and Bolt Food

Free HTML templates list for Startups

Free HTML templates list for startup. A complete list with free resources to build your next startup's website and gain the traction to the sky.

Deal with client requests in SaaS

How to deal with client requests in Saas which are seeing only their interests, not the product interest.

The first client of LoyalXpert is not answering anymore

Trying to implement LoyalXpert app, I lost my first customer, he's not answering anymore

Experiments with Tiktok Ads

Recently tried out TikTok ads for the first time and here are some of my learnings and challenges

People don’t care about you, until they know you care about them.

People don’t care about you, until they know you care about them. The same happens in business, you need to take care of your clients.

The One Word That Can Ruin Your SaaS Business Anyone

As a SaaS founder, you probably know how important it is to have a clear and specific target market for your product.

How I got my digital certificate connected it with ANAF

How I got my digital certificate from certSIGN and connected it with ANAF

The Ultimate List of Company Directories to Boost Your Networking

Discover a wide range of company directories to boost your business's visibility and connect with potential clients.

Discover the Best Free AI Art Tools for Your Next Masterpiece

Explore a curated collection of the finest free AI art tools, designed to help you bring your artistic vision to life.