How to download a file from a path using JavaScript

In this example shows, how to download a file from a path when click on a link using JavaScript Fetch API. To download a file using the Fetch API in JavaScript, we can make a request to the server to get the file content and then use the response to initiate the download.

Here are the steps to dowload a file using fetch api:
  • Make a request to the server and get the file content
  • Convert the response to a Blob
  • Create an <a> (anchor) element to download
<input type='button' onclick="downloadFile('files/sample.pdf');" value='Download PDF' >

<input type='button' onclick="downloadFile('files/5.png');" value='Download Image' >

async function downloadFile(path){
  await fetch(path, { method: 'GET', })
      throw new Error(response.statusText);
      return response.blob();
      var fileName = path.replace(/^.*[\\/]/, '');
      const url = window.URL.createObjectURL(response);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = fileName;
    .catch(error =>{
      console.error('Error downloading file:', error)