How to download file using JavaScript

By FoxLearn 10/22/2024 10:04:29 AM   2
To download a file using JavaScript, you can create an anchor element (<a>) and trigger a click event on it.

Downloading a File from a URL

If you want to download a file from a specific URL, you can create a downloadFile method like this:

function downloadFile(url, filename) {
    const a = document.createElement('a');
    a.href = url;
    a.download = filename; // Specify the file name
    a.setAttribute('target', '_blank');
    a.click(); // Trigger the download
    URL.revokeObjectURL(href);
}

// Usage
downloadFile('https://example.com/file.pdf', 'your_filename.pdf');

Using Blob to download file

A Blob (Binary Large Object) is a data type used to store binary data. When you use the `fetch` API to request data, the response can be converted to a Blob type, allowing you to handle binary data effectively.

If you want to download data generated in the browser, you can create a Blob:

html

<button>download file with blob</button>

Javascript

function downloadFile(url, fileName) {
  fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
    .then(res => res.blob())
    .then(res => {
      const a = document.createElement('a');
      a.setAttribute('download', fileName);
      const href = URL.createObjectURL(res);
      a.href = href;
      a.setAttribute('target', '_blank');
      a.click();
      URL.revokeObjectURL(href);
    });
};

//Usage

document.querySelector('button').onclick =function () {
  downloadFile('https://example.com/file.pdf', 'file.pdf');
}

We will use fetch API to download the script file, then transform the data to a blob type.

Finally, Convert the blob object to a string by using URL.createObjectURL().

You need to create an <a> element to download the string.

The download functionality only works for same-origin URLs. If the file is from a different origin, the browser will open it instead of downloading it.

function downloadFile(data, filename) {
    const blob = new Blob([data], { type: 'text/plain' }); // Change MIME type as needed
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url); // Clean up the URL
}

Usage

const textData = "Hello, Javascript !";
downloadBlob(textData, 'example.txt');

If you are downloading files from a different origin, ensure that the server supports CORS.

Downloading a file and converting it to Blob format can help bypass cross-domain restrictions in browsers. However, for large files, the download may take longer, and it's important to provide user prompts to avoid being perceived as a bug.