通过ajax调用php下载文件

时间:2011-07-12 17:55:41

标签: php javascript ajax download

我有一个按钮,onclick会调用ajax函数。

这是我的ajax功能

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的末尾运行它,它会将file.csv的内容输出到页面(进入ajaxDiv)而不是下载。

有没有办法强制下载csv.php末尾的文件?

5 个答案:

答案 0 :(得分:40)

AJAX不用于下载文件。弹出一个新窗口,下载链接作为其地址,或document.location = ...

答案 1 :(得分:20)

使用jQuery的一个非常简单的解决方案:

在客户端:

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

并且在服务器端,请确保您发送回正确的Content-Type标头,以便浏览器知道其附件并开始下载。

答案 2 :(得分:12)

@joe:非常感谢,这是一个很好的抬头!

我遇到了一个稍微难点的问题: 1.发送带有POST数据的AJAX请求,以便服务器生成ZIP文件 2.得到回复 3.下载ZIP文件

这就是我如何做到的(使用JQuery来处理AJAX请求):

  1. 首发帖子请求:  

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

  2. “request / url”处理zip创建(关于主题,因此我不会发布完整代码)并返回以下JSON对象。类似的东西:

    <iframe/>

    “请求/下载”可以根据需要执行一些安全检查,并生成文件传输:

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

答案 3 :(得分:9)

我用隐藏的iframe完成了这个。我使用perl,而不是php,所以只提供概念,而不是代码解决方案。

客户端向服务器发送Ajax请求,导致生成文件内容。它在服务器上保存为临时文件,文件名将返回给客户端。

客户端(javascript)接收文件名,并将iframe src设置为将传递文件的某个URL,如:

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

服务器篡改文件,取消链接,并使用这些标头将流发送到客户端:

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

像魅力一样。

答案 4 :(得分:2)

您无法直接通过ajax下载文件。

您可以在页面上放置一个链接,其中包含您文件的URL(从ajax调用返回)或另一种方法是使用隐藏的iframe并设置{{1}的源的URL动态的。这样您就可以在不刷新页面的情况下下载文件。

这是代码

iframe
相关问题