Home > Web Front-end > JS Tutorial > How Can I Trigger a File Download Using AJAX, and What Are the Best Methods?

How Can I Trigger a File Download Using AJAX, and What Are the Best Methods?

Barbara Streisand
Release: 2024-12-06 02:04:10
Original
540 people have browsed it

How Can I Trigger a File Download Using AJAX, and What Are the Best Methods?

AJAX-Driven File Download: A Guide

In the realm of web development, arises the need to download files directly from the server using an AJAX request. To achieve this, various approaches can be utilized.

One standard approach involves initiating an AJAX request upon clicking a button. Here's a script that attempts this:

var xhr = new XMLHttpRequest();
xhr.open("GET", "download.php");
xhr.send();
Copy after login

To serve the file for download, a PHP script like this can be employed:

<?php
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename= file.txt");
header("Content-Transfer-Encoding: binary");    
readfile("file.txt");
?>
Copy after login

However, this method may not produce the desired behavior. Therefore, an alternative strategy is required.

Updated Solution: Introducing the download Attribute

Emerging in the HTML5 landscape is the download attribute. Supported by prominent browsers such as Firefox and Chrome (and soon IE11), this attribute provides a more streamlined solution for file downloads.

<a href="file.txt" download="file.txt">Download File</a>
Copy after login

As long as the file resides on the same origin as the website, it can be downloaded using this attribute.

Legacy Solution: Utilizing AJAX and Window Redirect

Before the advent of the download attribute, a workaround involved employing an AJAX request or window.location manipulation.

$.ajax({
    url: 'download.php',
    type: 'POST',
    success: function() {
        window.location = 'download.php';
    }
});
Copy after login

However, using window.location directly is a more efficient solution in this context.

The above is the detailed content of How Can I Trigger a File Download Using AJAX, and What Are the Best Methods?. 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