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
Release: 2024-12-28 10:30:13
Original
493 people have browsed it

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())
    Copy after login
  2. Create an object URL for the file:

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

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

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

     alert('your file has downloaded!');
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template