微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过Ajax和PHP强制下载

我想创建一个下载脚本,允许强制下载JPG.
这是我的PHP脚本:
<?PHP
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Content-Description: File Transfer");
    header("Content-Type: image/jpg");
    header('Content-disposition: attachment; filename="'.basename($GET['a']).'"');
    header("Content-transfer-encoding: binary");
    header("Content-Length: ".filesize(($GET['a']));
    readfile(($GET['a']);
?>

这是我的js代码代码段:

function downloadFile(a){
    document.location = "download.PHP?a="+ a;
}

使用此代码示例没有任何反应.如果我将结果附加到HTML标记中,它会显示文件内容.

任何想法如何教浏览器下载此文件

编辑:脚本更新

您无法使用ajax下载文件.所以,如果你有一些应该在ajax上发生的事情,你应该返回url作为响应并应用它像document.location =“url”来开始下载过程.

这里有一点说明.我记得,如果不是通过用户点击启动浏览器,它将阻止文件下载.所以,这将工作正常:

.click(function(){
   document.location = "download url"
})

但如果它不是由用户点击启动,它将被阻止.所以,这样的代码

.click(function(){
       $.ajax({...,success:function(download_url_from_server){
           document.location = download_url_from_server;
       }});           
    })

将被浏览器阻止.因此,如果您想通过帖子传递一些数据,您可以使用< form target =“...”将表单提交到隐藏的iframe或空白页面

function checkToken(token){
    var $form = $("#downloadForm");
    if ($form.length == 0) {
        $form = $("<form>").attr({ "target": "_blank","id": "downloadForm","method": "POST","action": "script.PHP" }).hide();
        $("body").append($form);
    }
    $form.find("input").remove();
    var args = { a: "checkToken",b: token }
    for (var field in args) {
        $form.append($("<input>").attr({"value":args[field],"name":field}));
    }
    $form.submit();
}

在script.PHP中,如果令牌为Ok,则需要立即执行download.PHP中的代码,或者重定向下载脚本:

header("Location: download.PHP?a=" . $filename)

原文地址:https://www.jb51.cc/ajax/160196.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐