Download URL files using JS

edited July 2023 in PHP

The download function takes two parameters: 'URL' (the URL of the file to be downloaded) and 'filename' (the desired name of the downloaded file).

It uses the 'fetch' function to make a network request to the provided URL .

The first '.then' block processes the response object by calling the '.blob()' method on it.

The second '.then' block handles the resolved Blob. It creates a new '<a>' element using 'document.createElement("a")'.

It sets the 'href' attribute of the <a> element to the temporary URL created from the Blob using 'URL.createObjectURL(blob)'.

The download attribute of the <a> element is set to the provided 'filename' . This will be the name of the file when it's downloaded by the user.

The function then initiates the download by programmatically clicking on the element using 'link.click()' . This triggers the download process, and the browser will prompt the user to save the file with the specified filename.

Code:

function download(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(console.error);

}


Note:

Keep in mind that for this function to work correctly, it should be called in response to a user interaction, such as a button click.

Sign In or Register to comment.