通过ajax调用php下载文件

I have a button and onclick it will call an ajax function.

Here is my 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);
}

I create the csv file based on the user input. After it's created I want it to prompt download or force download(preferably force). I am using the following script at the end of the php file to download the file. If I run this script in a separate file it works fine.

$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";

But If I run it at the end of csv.php it outputs the contents of the file.csv into the page(into the ajaxDiv) instead of downloading.

Is there a way to force download the file at the end of csv.php?

5个回答



AJAX不用于下载文件。 弹出一个新窗口,下载链接作为其地址,或者执行 document.location = ... </ code>。</ p>
</ div>

展开原文

原文

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

duanbi3385
duanbi3385 为什么AJAX不能下载文件?
2 年多之前 回复
doushenyi9104
doushenyi9104 我认为技术上最好设置window.location; 看到这个讨论:stackoverflow.com/questions/7857878 / ...
7 年多之前 回复



您无法直接通过ajax下载文件。</ p>

您可以输入链接 带有文件URL的页面(从ajax调用返回)或其他方式是使用隐藏的 iframe </ code>并动态设置 iframe </ code>的源代码的URL。 这样你就可以在不刷新页面的情况下下载文件了。</ p>

这是代码</ p>

  $ .ajax({
url: “yourURL.php”,
类型:“GET”,
成功:函数(数据){
$(“#iframeID”)。attr('src','downloadFileURL');
}
} );
</ code> </ pre>
</ div>

展开原文

原文

You can't download the file directly via 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. This way you can download the file without refreshing the page.

Here is the code

$.ajax({
    url : "yourURL.php",
    type : "GET",
    success : function(data) {
        $("#iframeID").attr('src', 'downloadFileURL');
    }
});

dongtuo5611
dongtuo5611 在你的ajax成功响应中你可以设置隐藏的iframe src
6 年多之前 回复
dongpo1846
dongpo1846 发布相关代码有助于说明您在此处要说的内容。
6 年多之前 回复

I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

$('iframe_dl').src="/app?download=1&filename=" + the_filename

Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

Works like a charm.

dounai1986
dounai1986 “啜饮”一个技术术语?
大约一年之前 回复

@joe : Many thanks, this was a good heads up!

I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

So that's how I did it (using JQuery to handle the AJAX request):

  1. Initial post request:

    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);

The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

 //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;

The "request/download" can perform some security checks, if needed, and generate the file transfer:

$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);
  }

}
duanchao1002
duanchao1002 只需要改变一个? 用于查询字符串。 感谢您对此的精彩帮助! - 我试着做一个编辑,但它是一个很小的它不会让我! $ dlink ='http://'。$_SERVER [“SERVER_NAME”]。'/ request / download?file ='。$ zipid;
3 年多之前 回复



使用jQuery的一个非常简单的解决方案:</ p>

在客户端:</ p> \ n

  $('。act_download_statement')。click(function(e){
e.preventDefault();
form = $('#my_form');
form.submit( );
});
</ code> </ pre>

在服务器端,确保发回正确的 Content-Type </ code>标题, 浏览器将知道其附件,下载将开始。</ p>
</ div>

展开原文

原文

A very simple solution using jQuery:

on the client side:

$('.act_download_statement').click(function(e){
    e.preventDefault();
    form = $('#my_form');
    form.submit();
});

and on the server side, make sure you send back the correct Content-Type header, so the browser will know its an attachment and the download will begin.

douji2520
douji2520 如果我想显示一些加载器暂时的业务逻辑正在实现和创建文件内容。
5 年多之前 回复
dsu89430
dsu89430 代码很好,但是发生错误的是它被重定向到一个不需要的错误页面
大约 6 年之前 回复
dongli9894
dongli9894 你能提供更多的细节,并提供一些关于两端发生的事情的代码吗?
6 年多之前 回复
duan7772
duan7772 +1这篇文章更具技术性,是一个很好的技巧
6 年多之前 回复
dsdtszi0520538
dsdtszi0520538 +1这对于我将数据发布到服务器并获取ZIP文件下载作为响应非常有用。 没有页面重新加载。
7 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐