Download File from URL and Save in JavaScript

// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Set the URL to download
xhr.open(‘GET’, ‘http://example.com/file.txt’, true);

// Set the responseType to blob
xhr.responseType = ‘blob’;

// Onload function
xhr.onload = function(e) {
if (this.status == 200) {
// Create a new Blob object using the response data of the onload object
var blob = new Blob([this.response], {type: ‘text/plain’});

// Create a link element, hide it, direct it towards the blob, and use it to download the data
var a = document.createElement(“a”);
a.href = window.URL.createObjectURL(blob);
a.download = “file.txt”;
a.style.display = “none”;
document.body.appendChild(a);

// Click the download link
a.click();

// Cleanup
delete a;
}
};

// Send XHR
xhr.send();

Downloading files from URLs is an everyday job in web development, and JavaScript provides several methods to do this. Whether you want to fetch a PDF, image, or any other type of file, this tutorial guide will show you several different ways to download files from a URL and save them in JavaScript.

And, now you will learn several ways how to download and save a file from a URL in JavaScript.

Table of Contents

You can download and save files from URLs in JavaScript using methods such as anchor elements, the Fetch API, and XMLHttpRequest, Methods are following with examples:

  1. Using the Anchor Element (<a>)
  2. Fetch API and Blob
  3. XMLHttpRequest
  4. Libraries for File Download

1. Using the Anchor Element (<a>)

The simplest way to download a file from a URL in JavaScript is by utilizing the anchor element (<a>). This method works best for publicly accessible files that don’t require any authentication.

<!-- HTML -->
<a id="downloadLink" href="your_file_url_here" download="desired_file_name.extension">Download File</a>
// JavaScript (optional if you want to modify the link dynamically)
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = 'new_file_url_here';

In this method, the download attribute specifies the desired name for the downloaded file. When the user clicks on the anchor link, the browser will automatically prompt for download.

2. Fetch API and Blob

The Fetch API and the Blob object allow you to programmatically download files and handle more complex scenarios such as authentication or dynamically generated files.

function downloadFileFromURL(url, fileName) {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
    })
    .catch(error => console.error('Error downloading file:', error));
}

// Usage
downloadFileFromURL('your_file_url_here', 'desired_file_name.extension');

In this method, we use Fetch API to download file from URL. The response is converted to a Blob object, which is used to construct a temporary object URL. This URL is bound to a dynamically created anchor (<a>) element, and when the user clicks on it, the file will be downloaded.

3. XMLHttpRequest

The older XMLHttpRequest object can also be used to download files from url, although it is considered less modern than the Fetch API.

function downloadFileFromURL(url, fileName) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';

  xhr.onload = function () {
    if (xhr.status === 200) {
      const blob = new Blob([xhr.response]);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
    } else {
      console.error('Error downloading file:', xhr.statusText);
    }
  };

  xhr.send();
}

// Usage
downloadFileFromURL('your_file_url_here', 'desired_file_name.extension');

The XMLHttpRequest method is similar to the Fetch API approach. However, error detection requires manual handling of the status codes.

4. Libraries for File Download

Many JavaScript libraries simplify file download from URL functions and provide additional features. Some popular ones include:

  • Axios: A promise-based HTTP client that can handle file downloads along with other HTTP requests.
  • File-saver: A library for saving files on the client-side. It provides a simple API for saving blobs as files.

To use these libraries, first, include them in your project via CDN or package manager (for example, npm, yarn). Then, follow their documentation to easily download files from URLs.

Conclusion

Downloading files from URLs in JavaScript can be performed using a types of method, depending on your needs and the complexity of the task. Anchor elements (<a>), the Fetch API, and XMLHttpRequest are the primary built-in options, while libraries such as axios and file-saver provide more advanced functionality. Choose the method that best suits your needs and start enabling seamless file downloads in your web applications.

Recommended Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?