猿问
下载APP

通过ajax调用php下载文件

通过ajax调用php下载文件

我有个按钮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末尾的文件?


慕仰8121524
浏览 589回答 3
3回答

大话西游666

Ajax不适合下载文件。弹出一个以下载链接作为其地址的新窗口,或者执行以下操作document.location = ....

catspeake

使用jQuery的一个非常简单的解决方案:在客户端:$('.act_download_statement').click(function(e){     e.preventDefault();     form = $('#my_form');     form.submit();});在服务器端,确保发送正确的Content-Type标题,因此浏览器将知道它的附件和下载将开始。

至尊宝的传说

我遇到了一个稍微困难的问题:1.发送带有POST数据的Ajax请求,让服务器生成一个ZIP文件;2.获得响应;3.下载ZIP文件所以我就是这样做的(使用JQuery来处理Ajax请求):初步员额请求:var parameters = { &nbsp; &nbsp; pid &nbsp; &nbsp; : "mypid", &nbsp; "files[]": ["file1.jpg","file2.jpg","file3.jpg"]}var options = { &nbsp; url: "request/url",//replace with your request url &nbsp; type: "POST",//replace with your request type &nbsp; data: parameters,//see above &nbsp; context: document.body,//replace with your contex &nbsp; success: function(data){ &nbsp; &nbsp;if (data) { &nbsp; &nbsp; &nbsp; &nbsp;if (data.path) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Create an hidden iframe, with the 'src' attribute set to the created ZIP file. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var dlif = $('<iframe/>',{'src':data.path}).hide(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Append the iFrame to the context &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.append(dlif); &nbsp; &nbsp; &nbsp; &nbsp;} else if (data.error) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert(data.error); &nbsp; &nbsp; &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert('Something went wrong'); &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp;}}};$.ajax(options);“requesturl”处理zip创建(OFF主题,所以我不会发布完整的代码)并返回以下JSON对象。类似于:&nbsp;//Code&nbsp;to&nbsp;create&nbsp;the&nbsp;zip&nbsp;file &nbsp;//...... &nbsp;//Id&nbsp;of&nbsp;the&nbsp;file &nbsp;$zipid&nbsp;=&nbsp;"myzipfile.zip" &nbsp;//Download&nbsp;Link&nbsp;-&nbsp;it&nbsp;can&nbsp;be&nbsp;prettier &nbsp;$dlink&nbsp;=&nbsp;'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid; &nbsp;//JSON&nbsp;response&nbsp;to&nbsp;be&nbsp;handled&nbsp;on&nbsp;the&nbsp;client&nbsp;side &nbsp;$result&nbsp;=&nbsp;'{"success":1,"path":"'.$dlink.'","error":null}'; &nbsp;header('Content-type:&nbsp;application/json;'); &nbsp;echo&nbsp;$result;如果需要,“请求/下载”可以执行一些安全检查,并生成文件传输:$fn&nbsp;=&nbsp;$_GET['file'];if&nbsp;($fn)&nbsp;{ &nbsp;&nbsp;//Perform&nbsp;security&nbsp;checks &nbsp;&nbsp;//.....check&nbsp;user&nbsp;session/role/whatever &nbsp;&nbsp;$result&nbsp;=&nbsp;$_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn; &nbsp;&nbsp;if&nbsp;(file_exists($result))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;header('Content-Description:&nbsp;File&nbsp;Transfer'); &nbsp;&nbsp;&nbsp;&nbsp;header('Content-Type:&nbsp;application/force-download'); &nbsp;&nbsp;&nbsp;&nbsp;header('Content-Disposition:&nbsp;attachment;&nbsp;filename='.basename($result)); &nbsp;&nbsp;&nbsp;&nbsp;header('Content-Transfer-Encoding:&nbsp;binary'); &nbsp;&nbsp;&nbsp;&nbsp;header('Expires:&nbsp;0'); &nbsp;&nbsp;&nbsp;&nbsp;header('Cache-Control:&nbsp;must-revalidate,&nbsp;post-check=0,&nbsp;pre-check=0'); &nbsp;&nbsp;&nbsp;&nbsp;header('Pragma:&nbsp;public'); &nbsp;&nbsp;&nbsp;&nbsp;header('Content-Length:&nbsp;'&nbsp;.&nbsp;filesize($result)); &nbsp;&nbsp;&nbsp;&nbsp;ob_clean(); &nbsp;&nbsp;&nbsp;&nbsp;flush(); &nbsp;&nbsp;&nbsp;&nbsp;readfile($result); &nbsp;&nbsp;&nbsp;&nbsp;@unlink($result); &nbsp;&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答