[英]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.