Others



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
Example
<input type='button' onclick="downloadFile('files/sample.pdf');" value='Download PDF' >

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

<script>
async function downloadFile(path){
  await fetch(path, { method: 'GET', })
    .then(response=>{
      if(!response.ok){
      throw new Error(response.statusText);
      }
      return response.blob();
    })
    .then(response=>{
      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;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    })
    .catch(error =>{
      console.error('Error downloading file:', error)
    });
}
</script>