2012-12-14 102 views
1

可能重复:
Downloading Via JQuery AJAX Post not workingPHP AJAX jQuery的 - 文件下载问题

filedownload.php低于snippent。

$file = 'cut.png'; 
header("Content-Type: image/png"); 
header('Content-Disposition: attachment; filename="'.$file.'"'); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 
readfile($file); 
exit(); 

AJAX调用

jQuery.post('filedownload.php',{    
    'file' : result // not used for the time being      
}); 

我做一个AJAX调用filedownload.php文件。它不允许用户下载文件。但是如果我直接运行php,它允许用户下载文件。可能是什么问题 ?

我想使用核心函数而不是使用jQuery插件。如果这是不可能的,一个插件会好起来的。

鉴于我使用ajax,因为页面无法刷新。

+0

校验码了这一点:http://stackoverflow.com/questions/676348/allow - 用户对下载文件使用的Ajax –

回答

3

的问题

让我们生产力的web应用程序的例子,如电子表格 编辑器,其中有打开,保存,进口和出口的能力。 打开和保存选项将涉及从 数据库加载电子表格,而导入和导出用户计算机上的本地文件。要实现导出行为,您可以决定 用户应该首先保存其电子表格,允许您将数据从后端导出到文件。但我们假设 ,而不是您希望允许用户导出其数据而不保存, 也许可以让他们选择在本地工作,而不需要在服务器上存储数据 。为了做到这一点,你需要发送 当前的电子表格数据到后端,并接收文件到 下载。不幸的是,这不能使用Ajax来处理,因为 Ajax只能以文本形式接收响应。在要保存的数据相当长的情况下,这会产生相当大的问题。

的解决方法

为了使的要求,你需要使用GET或POST HTTP请求进行定期(不阿贾克斯)。如果数据相当短,您可能会通过GET请求(可能只需将 Window.location设置为您的导出网址),但由于浏览器对GET请求长度的限制不同,最有可能需要POST 。 以下插件允许您发出请求,以类似于jQuery本机Ajax函数的语法返回文件 。

jQuery的哪一个能解决问题

jQuery.download = function(url, data, method){ 
    //url and data options required 
    if(url && data){ 
     //data can be string of parameters or array/object 
     data = typeof data == 'string' ? data : jQuery.param(data); 
     //split params into form inputs 
     var inputs = ''; 
     jQuery.each(data.split('&'), function(){ 
      var pair = this.split('='); 
      inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
     }); 
     //send request 
     jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>') 
     .appendTo('body').submit().remove(); 
    }; 
}; 

如何调用

$.download('filedownload.php','filename='+filename); 

Read more