Enable File Download with Ajax
In the era of asynchronous programming, it's often necessary to download a file without interrupting user interaction. This question explores how to download a file using Ajax while prompting the user to save the file locally.
In the provided Struts2 action, a file can be downloaded using a stream result. However, directly posting to this action using jQuery will render the file in-browser as binary stream. To trigger the file download window, a different approach is required.
Modern Browser Solution
Modern browsers offer a more straightforward solution. Using the fetch() API, you can retrieve the file as a blob and create a temporary URL for download.
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // Set the download filename a.download = 'todo-1.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('File download complete!'); }) .catch(() => alert('File download failed!'));
This approach requires a modern browser with support for the fetch() API and createObjectURL() method.
The above is the detailed content of How Can I Trigger a File Download Using Ajax Without Interrupting User Interaction?. For more information, please follow other related articles on the PHP Chinese website!