加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过Ajax和PHP强制下载

发布时间:2020-12-16 03:08:09 所属栏目:百科 来源:网络整理
导读:我想创建一个下载脚本,允许强制下载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"); heade
我想创建一个下载脚本,允许强制下载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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读