Download a file using Javascript


In JavaScript, you can download a file from the server using the XMLHttpRequest object to make an AJAX request to the server and then save the response to a file.

Here is an example of how to download a file using JavaScript:

function downloadFile() {
  var xhr = new XMLHttpRequest();'GET', 'path/to/file.ext', true);
  xhr.responseType = 'blob';

  xhr.onload = function() {
    if (this.status === 200) {
      var blob = new Blob([this.response], { type: 'application/octet-stream' });
      var url = URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = url; = 'filename.ext';


In the above example, the downloadFile() function creates a new XMLHttpRequest object and opens a GET request to the server using the open() method. The responseType property is set to ‘blob’ to indicate that the response should be treated as a binary data.

When the onload event fires, the function checks the status of the response and creates a new Blob object using the response data. The URL.createObjectURL() method is used to create a URL for the Blob object, which is then used to create a new a element with the href attribute set to the URL of the Blob. The download attribute is set to the filename of the file to be downloaded. The a element is added to the document, clicked programmatically using the click() method, and then removed from the document. Finally, the URL.revokeObjectURL() method is used to release the object URL.

Note that the above example uses the application/octet-stream MIME type to force the browser to download the file. You can change this to a more appropriate MIME type for your file. Also, the URL.createObjectURL() method is supported in modern browsers. If you need to support older browsers, you may need to use a different method to create a download link, such as using the data URI scheme.