通过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)

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...