$.ajax({ url: '/api/generate-report', method: 'GET', xhrFields: { responseType: 'blob' // Essential for binary data }, success: function(data) { const a = document.createElement('a'); const url = window.URL.createObjectURL(data); a.href = url; a.download = 'MyReport.xlsx'; document.body.append(a); a.click(); window.URL.revokeObjectURL(url); // Clean up memory $(a).remove(); }, error: function() { alert('Download failed!'); } }); Use code with caution.
Allows jQuery to read custom headers like filenames from the response. Summary Comparison Table Static public files Low (No headers) Window.location Simple redirects AJAX + Blob Protected or Dynamic data High (Auth headers) Full (Progress bars) jquery file download example
To ensure the browser correctly identifies the file, your backend must provide specific HTTP headers . Even if you use jQuery, these server-side headers are critical: Content-Type Defines the file type (e.g., application/pdf ). Content-Disposition Set to attachment; filename="file.zip" to force download. Access-Control-Expose-Headers Even if you use jQuery, these server-side headers
It allows you to send Authorization tokens in your AJAX request, which is impossible with standard link clicks. 3. Monitoring Progress: Adding a Download Progress Bar handling dynamic data
$.ajax({ url: 'large-video-file.mp4', method: 'GET', xhrFields: { responseType: 'blob' }, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) * 100; $('.progress-bar').css('width', percentComplete + '%'); console.log('Download Progress: ' + percentComplete + '%'); } }, false); return xhr; }, success: function(blob) { // Trigger download as shown in Method 2 } }); Use code with caution. 4. Handling Backend Headers
Integrating file downloads into web applications used to be a simple matter of using anchor tags. However, modern requirements—such as downloading files after an AJAX request, handling dynamic data, or adding security headers—require more sophisticated techniques. This guide explores the most effective ways to implement a , ranging from basic links to advanced Blob-based methods. 1. The Direct Method: Simple Anchor Tags