【问题标题】:PHP AJAX Jquery - File download issue [duplicate]PHP AJAX Jquery - 文件下载问题[重复]
【发布时间】:2012-12-14 06:54:03
【问题描述】:

可能重复:
Downloading Via JQuery AJAX Post not working

filedownload.php 有以下片段。

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

我对@9​​87654325@ 文件进行了ajax 调用。它不允许用户下载文件。但如果我直接运行 php,它允许用户下载文件。可能是什么问题 ?

我想使用核心功能而不是使用 jQuery 插件。如果不可能,一个插件就可以了。

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

【问题讨论】:

标签: php jquery ajax file download


【解决方案1】:

问题

让我们以电子表格等生产力网络应用为例 编辑器,具有打开、保存、导入和导出功能。这 打开和保存选项将涉及从 数据库,而导入和导出处理本地文件 用户的机器。要实现导出行为,您可能会决定 用户应该首先保存他们的电子表格,允许 您将数据从后端导出到文件。但是让我们假设 相反,您希望允许用户在不保存的情况下导出他们的数据, 也许是为了给他们提供在当地工作的选择 在服务器上存储数据。为此,您需要发送 当前电子表格数据到后端并接收文件到 下载。不幸的是,这不能使用 Ajax 来处理,因为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2011-04-05
    • 2023-04-10
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多