[英]Download file through an ajax call php
我有一个按钮onclick
它将调用 ajax function。
这是我的 ajax function
function csv(){
ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests
postdata = "data=" + document.getElementById("id").value;
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('ajaxDiv');
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST","csv.php",false);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(postdata);
}
我根据用户输入创建了 csv 文件。 创建后我希望它提示下载或强制下载(最好是强制)。 我在 php 文件末尾使用以下脚本来下载文件。 如果我在一个单独的文件中运行这个脚本,它就可以正常工作。
$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';
if (file_exists($fileName)) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$downloadFileName);
ob_clean();
flush();
readfile($fileName);
exit;
}
echo "done";
但是,如果我在 csv.php 的末尾运行它,它会将文件 .csv 的内容输出到页面(到 ajaxDiv 中)而不是下载。
有没有办法强制下载csv.php结尾的文件?
AJAX 不适用于下载文件。 弹出一个新的 window 并以下载链接作为其地址,或者执行document.location =...
。
使用 jQuery 的一个非常简单的解决方案:
在客户端:
$('.act_download_statement').click(function(e){
e.preventDefault();
form = $('#my_form');
form.submit();
});
在服务器端,确保发回正确的Content-Type
header,这样浏览器就会知道它的附件并开始下载。
@joe:非常感谢,这是一个很好的提醒!
我遇到了一个稍微困难的问题:1. 发送带有 POST 数据的 AJAX 请求,以便服务器生成 ZIP 文件 2. 得到响应 3. 下载 Z4348F938BBDDD8475E967CCB47ECB234 文件
所以我就是这样做的(使用 JQuery 来处理 AJAX 请求):
初始发帖请求:
var parameters = { pid: "mypid", "files[]": ["file1.jpg","file2.jpg","file3.jpg"] }
var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('
<iframe/>
',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);
“请求/url”处理 zip 创建(题外话,所以我不会发布完整代码)并返回以下 JSON object。 就像是:
//Code to create the zip file
//......
//Id of the file
$zipid = "myzipfile.zip"
//Download Link - it can be prettier
$dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
//JSON response to be handled on the client side
$result = '{"success":1,"path":"'.$dlink.'","error":null}';
header('Content-type: application/json;');
echo $result;
如果需要,“请求/下载”可以执行一些安全检查,并生成文件传输:
$fn = $_GET['file'];
if ($fn) {
//Perform security checks
//.....check user session/role/whatever
$result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
if (file_exists($result)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($result));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($result));
ob_clean();
flush();
readfile($result);
@unlink($result);
}
}
我通过隐藏的 iframe 完成了这项工作。 我使用 perl,而不是 php,所以只会给出概念,而不是代码解决方案。
客户端向服务器发送 Ajax 请求,导致生成文件内容。 这在服务器上保存为临时文件,并将文件名返回给客户端。
客户端(javascript)接收文件名,并将 iframe src 设置为将传递文件的 url,例如:
$('iframe_dl').src="/app?download=1&filename=" + the_filename
服务器 slurps 文件,取消链接,并将 stream 发送到客户端,带有以下标头:
Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'
奇迹般有效。
您不能直接通过 ajax 下载文件。
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. 这样您就可以在不刷新页面的情况下下载文件。
这是代码
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
你可以这样做:
在您的 PHP REST api 上:(后端)
header('Content-Description:File Transfer');
header('Content-Type:application/octet-stream');
header('Content-Disposition:attachment; filename=' . $toBeDownloaded);
header('Content-Transfer-Encoding:binary');
header('Expires:0');
header('Cache-Control:must-revalidate');
header('Pragma:public');
header('Content-Length:'.filesize($toBeDownloaded));
readfile($toBeDownloaded);
exit;
在您的 javascript 代码上:(前端)
const REQUEST = `API_PATH`;
try {
const response = await fetch(REQUEST, {
method: 'GET',
})
const fileUploaded = await response.blob();
const url = window.URL.createObjectURL(fileUploaded);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'YOUR_FILE_NAME_WITH_EXTENSION');
document.body.appendChild(link);
link.click();
} catch (error) {
console.log(error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.