All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Download File From URL JavaScript

Last Updated : Mar 11, 2024

Download File From URL JavaScript

In this article we will show you the solution of download file from URL JavaScript, in this article we will learn use of Fetch API to download file from URL in JavaScript. JavaScript's Fetch API, a cutting-edge and potent tool, makes it simple to send network queries and manage results.

We will look towards how to use Fetch API to download any file, including photo, document, and other file types, from a particular URL.

Basic methodology which will show us how to download files from a URL using JavaScript:

Using Fetch API, will send a GET request to the particular URL.

Will collect server’s response, which will contain the file data.

To represent the file content, create a Blob object using the response information.

To produce a link that may be downloaded, create a URL object from the Blob.

Step By Step Guide On Download File From URL JavaScript :-

async function downloadURL(url,fileName) {
    try {
        const response = await fetch(url);
        const blob = await response.blob();
        const dLink = document.createElement("a");
        dLink.href = URL.createObjectURL(blob);
        dLink.download = fileName;
        dLink.click();
        URL.revokeObjectURL(dLink.href);
        }
    catch (error) {
        console.error("Error occurring while downloading the file:", error);
        }
    }
  1. For indicating asynchronous function, we use word “async” for function declaration. Await can be used with asynchronous methods to halt the execution until a Promise is fulfilled or denied.
  2. The function requires these two inputs, url: The download link for the file. fileName: This is the preferred filename for the downloaded file.
  3. A try-catch block is used inside the function to deal with any potential download-related issues.
  4. The try block contains, The specified url is used to fetch the file contents using the fetch() method. In order to wait for the Promise to resolve and receive the response object, the await keyword is used before fetch().
  5. The response data is then transformed into a Blob object by calling the response.blob() function. Once more, the await keyword is used before response.blob() to delay the retrieval of the blob object until the Promise has resolved.
  6. The function then does the following actions after getting the blob object, Using document, a new anchor (‘a’) element is document.createElement("a"). The file download will be started using this component.
  7. The object URL built with the help of URL.createObjectURL(blob) is set as the anchor element's href property. The file data is represented by this object URL as a Blob object.
  8. The given fileName is the value for the anchor element's download property. This attribute decides what the downloaded file's filename will be.
  9. Using document.body, the anchor element is added as a child to the document.body.appendChild(downloadLink).
  10. The anchor element receives a call to the click() method, which programmatically causes the element to experience a click event. The file is automatically downloaded to the user's device after this starts the download process.
  11. The URL.revokeObjectURL(downloadLink.href) method is used to release the object URL and release resources after the file download has been initiated.
  12. The catch block is activated if any errors are encountered while downloading, A record of the error is kept in the error variable.
  13. For printing an error message to the console, we have use console.error().

Conclusion :-

In this article, we will take a look after that how we use Fetch API to retrieve files from a URL in JavaScript.

In order to start the file download, we learnt how to perform a GET request, process the response, and build a downloadable link.

The Fetch API is an effective tool for file downloads and other web-related tasks since it makes the process of sending network requests and managing data simpler.

Your online apps may now incorporate file downloads with ease, giving users a smooth experience.

Although the Fetch API is well supported in contemporary browsers, you should always take your target audience's compatibility needs into account and, if necessary, provide fallbacks for older browsers.

With this understanding, you are prepared to use JavaScript and the Fetch API to add file downloading functionality to your online apps.

I hope this article on download file from URL JavaScript helps you and the steps and method mentioned above are easy to follow and implement.