Home > Web Front-end > JS Tutorial > How Can I Trigger a File Download Using Ajax Without Interrupting User Interaction?

How Can I Trigger a File Download Using Ajax Without Interrupting User Interaction?

Mary-Kate Olsen
Release: 2024-12-28 19:41:11
Original
687 people have browsed it

How Can I Trigger a File Download Using Ajax Without Interrupting User Interaction?

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!'));
Copy after login

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!

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