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

Tools for Analyzing Your Competition

Before knowing where your business stands, you should look at the market and your competition. You need to know what marketing tactics and strategies are working for your audience, what traffic the competition has, and how they position.

Free Online Photo Editor with Cool Effects | Edit Images Easily

Transform your images with our free online photo editor with cool effects. Add filters, adjust colors, and apply creative enhancements. Edit your photos easily and make them stand out.

How to find the size of a table in SQL?

Learn how to determine the size of a SQL table with this informative guide. Discover efficient methods for measuring table size.

MongoDB Query date by _id field

Query date by _id in mongodb. Straighforward guide to solve your issue right away.

Unleashing the Power of Free API for Scrape Reverse Geocoding

Learn how to harness the potential of reverse geocoding with our beginner's guide to scraping APIs for free. Unlock the power today.

Discover the Power of Whatsapp-web.js for Safe and Easy Automation

Automate WhatsApp with ease using Whatsapp-web.js, a NodeJS client library that connects through the official WhatsApp Web app, reducing ban risks. Perfect for user or business accounts.

Website tours js tools

Tools to create live tours for your web project using js libraries.

Unlocking SaaS Marketing Success: Essential Resources to Learn and Grow

Discover a comprehensive collection of valuable resources to master the art of SaaS marketing.

Where to launch your startup

Do you wanna launch grandiosely your startup? Get a list of platforms where people can discover your project and can push your project directly to the sky.

Email campaign improving my SaaS convertion - Manager Flota

Users subscribe to your SaaS, but don't let the money on your table. Here's how I do it!