Download a file using Javascript
javascriptIn 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();
xhr.open('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;
a.download = 'filename.ext';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
xhr.send();
}
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.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame