Home >Web Front-end >JS Tutorial >How Can I Asynchronously Download Files in a Struts2 Application Using Ajax?

How Can I Asynchronously Download Files in a Struts2 Application Using Ajax?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 10:30:13489browse

How Can I Asynchronously Download Files in a Struts2 Application Using Ajax?

Asynchronous File Download with Ajax

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:

  1. Use the fetch() API to fetch the file:

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(resp => resp.blob())
  2. Create an object URL for the file:

      .then(blob => {
     const url = window.URL.createObjectURL(blob);
  3. 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';
  4. Append the element to the document and click it:

     document.body.appendChild(a);
     a.click();
  5. Remove the object URL:

     window.URL.revokeObjectURL(url);
  6. Notify the user of the successful download:

     alert('your file has downloaded!');

Additional Considerations:

  • Ensure compatibility with the target browsers.
  • Handle large file downloads separately to avoid potential performance issues.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn