使用AJAX调用下载文件

时间:2012-07-27 09:04:36

标签: php javascript ajax download

我正在尝试将一些细节附加到文件中并添加以供下载。

我正在使用JavaScript和PHP。单击下载按钮,它将触发AJAX请求。

$.ajax({
  url:"php/test.php",
  type: 'POST',
  data: { totalQuery : test1, },

  success: function(finalEntityList){
  },
});

假设test.php有一行代码

$html="Test";

现在我想将其添加到文件中并使其可供下载。我已经使用了代码

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fwrite($output, $html);
fclose($output);

但是下载不会自动启动...我将使用firebug打开POST请求链接,以便下载将被启动..可能是什么错误?

2 个答案:

答案 0 :(得分:1)

也许您需要做的只是使用您的AJAX调用返回文件的路径,然后使用JavaScript来启动"使用以下之一下载 -

  • window.open
  • window.location.href
$.ajax({
  url:"php/test.php",
  type: 'POST',
  dataType: 'json',
  data: { totalQuery : test1, },

  success: function(response){
    // initiate download using direct path to file
    window.location.href = response.URL;
  }
});

现在,您的test.php文件只需要以JSON格式返回下载文件的URL路径 -

$filename = 'data.csv';
$path = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
echo json_encode(array('URL'=>$path.$filename));

您可以考虑将URL作为原始字符串返回 - 但我觉得使用JSON可能更好,因为您可以轻松地将其他信息添加到响应中而无需其他解析功能。所有这些使它成为一个更强大的选择。

答案 1 :(得分:0)

它需要更多参数和headerinfo:

$file = "data.csv";
$mime_type = "text/csv";
$size = filesize($file);
$name = rawurldecode($name);

@ob_end_clean(); //turn off output buffering to decrease cpu usage

// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');

/* The three lines below basically make the
download non-cacheable */
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
    list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
    list($range) = explode(",",$range,2);
    list($range, $range_end) = explode("-", $range);
    $range=intval($range);
    if(!$range_end)
    {
        $range_end=$size-1;
    } 
    else
    {
        $range_end=intval($range_end);
    }

    $new_length = $range_end-$range+1;
    header("HTTP/1.1 206 Partial Content");
    header("Content-Length: $new_length");
    header("Content-Range: bytes $range-$range_end/$size");
} 
else
{
    $new_length=$size;
    header("Content-Length: ".$size);
}

/* output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
    if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

    while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length))
    {
        $buffer = fread($file, $chunksize);
        print($buffer); //echo($buffer); // is also possible
        flush();
        $bytes_send += strlen($buffer);
    }
    fclose($file);
} 
else 
    die('Error - can not open file.');
相关问题