通过ajax获取临时下载url


Get temporary download url via ajax

我创建了一个PHP文件,它强制下载文件。当我通过ajax调用它时,它不起作用。谷歌表示ajax无法处理下载。我应该打开一个指向url的新窗口。

问题是该文件只有在php脚本运行时才存在。那么我该如何解决这个问题呢?

这是代码:

PHP:

<?php
    $jsonStr = $_POST['jsonStr'];
    $tmp_file = tempnam('/tmp', 'data-');
    $handle = fopen($tmp_file, 'a+');
    fwrite($handle, $jsonStr);
    if(!$tmp_file)
    {
        // File doesn't exist, output error
        die('file not found');
    }
    else
    {
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=iwbtg.lvl");
        header("Content-Type: text/plain");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($tmp_file);
    }
?>

JS:

...
var jsonStr = JSON.stringify(jsonObj);
// Request Level file
var http = createRequestObject();
http.open("POST", "save.php", false);
http.setRequestHeader("Content-Type", "application/x-www.form-urlencoded");
http.send("jsonStr=" + jsonStr);

document.location = "tmp/iwbtg.lvl";

您可以使用iframe来代替ajax。这不好看,但效果很好。你在iframe上发帖,不会重新加载整个页面,我想这是你首先要避免的。

如果您不想锁定UI或打开新窗口(因为操作需要时间),可以使用隐藏的iframe:

var downloadAsync = function(url, callback) { 
    var f = document.createElement('iframe'); 
    f.style.display = 'none'; 
    f.src = url; 
    f.onload = function() { 
        setTimeout(function() { 
            document.body.removeChild(f); 
        }, 500); 
        callback && callback(); 
    }; 
    document.body.appendChild(f); 
}; 

只需确保服务器使用Content-Disposition: attachment标头进行响应。