通过ajax获取临时下载URL

时间:2012-01-20 20:29:45

标签: php javascript ajax

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

问题是文件只在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";

2 个答案:

答案 0 :(得分:1)

您可以使用iframe代替ajax。这不是很漂亮,但效果很好。你发贴到iframe的帖子,并且不会重新加载整个页面,这是我想你首先要避免的。

答案 1 :(得分:0)

如果您不想锁定用户界面或打开新窗口(因为操作需要时间),您可以使用隐藏的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标头进行响应。

相关问题