Home >Web Front-end >JS Tutorial >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();
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"); ?>
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>
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'; } });
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!