Problem:
In a Struts2 application, a jQuery Ajax call retrieves binary stream data representing a file to be downloaded, but users are unable to save the file locally.
Solution:
Modern Browser Approach (2019 and Later)
For modern browsers, a simplified approach can be adopted:
Use the fetch() API to fetch the file:
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob())
Create an object URL for the file:
.then(blob => { const url = window.URL.createObjectURL(blob);
Create a hidden element and set its attributes:
const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = 'todo-1.json';
Append the element to the document and click it:
document.body.appendChild(a); a.click();
Remove the object URL:
window.URL.revokeObjectURL(url);
Notify the user of the successful download:
alert('your file has downloaded!');
Additional Considerations:
The above is the detailed content of How Can I Asynchronously Download Files in a Struts2 Application Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!