通过Ajax和PHP强制下载

Syl*_*ois 6 javascript php ajax jquery download

我想创建一个允许强制下载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']);
?>
Run Code Online (Sandbox Code Playgroud)

这是我的js代码的代码段:

function downloadFile(a){
    document.location = "download.php?a="+ a;
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:脚本更新

Vik*_* S. 20

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

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

.click(function(){
   document.location = "download url"
})
Run Code Online (Sandbox Code Playgroud)

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

.click(function(){
       $.ajax({...,
       success:function(download_url_from_server){
           document.location = download_url_from_server;
       }});           
    })
Run Code Online (Sandbox Code Playgroud)

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

 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();
}
Run Code Online (Sandbox Code Playgroud)

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

header("Location: download.php?a=" . $filename)
Run Code Online (Sandbox Code Playgroud)