In this digital age, file downloads are ubiquitous. With Ajax's capabilities, we can enhance the user experience by allowing file downloads asynchronously without interrupting webpage interactions.
The Problem
When using a Struts2 action for server-side file downloading, invoking the action via jQuery retrieves the data in a binary stream. However, the desired outcome is to trigger a file save dialog that allows users to save the file locally.
Modern Browser Solution
For modern browsers, the following approach is recommended:
<br>fetch('your-download-endpoint').then(resp => resp.blob()).then(blob => {<br> const url = window.URL.createObjectURL(blob);<br> const a = document.createElement('a');<br> a.style.display = 'none';<br> a.href = url;<br> a.download = 'your-file-name'; // Specify the desired filename<br> document.body.appendChild(a);<br> a.click();<br> window.URL.revokeObjectURL(url);<br>});<br>
This code creates a temporary URL for the blob data, which is then attached to an anchor element that is appended to the document body. Clicking on this hidden anchor element triggers the file save dialog, and once the download is complete, the temporary URL is revoked.
Considerations
While this approach works well for small to medium-sized files, it is important to consider memory consumption for very large downloads. If you anticipate large files, alternative techniques such as using an iframe and a cookie may be more suitable.
The above is the detailed content of How Can Ajax Asynchronously Trigger File Save Dialogs for Enhanced User Experience?. For more information, please follow other related articles on the PHP Chinese website!