从SQL数据库中的php脚本中弹出保存到文件..没有临时文件


Save to file popup from php script dipping in SQL Database ... no temp files

我有一个一般性的问题,不知道如何实现它

我想创建一个链接,允许用户下载从SQL数据库生成的文件。例如,用户在HTML表单上输入ID,单击"确定",就会出现"保存到文件"弹出窗口。文件中的数据将来自数据库。。。

我设法通过php将文件保存在服务器的tmp目录中,但我希望避免创建文件,即使是临时文件。

感谢

您只需将文件"传递"给用户,响应PHP脚本就会将其标头更新为文件类型。

以下是header()doc@php.net中的一个函数:

<?php
function downloadFile( $fullPath ){
  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');
  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
  // File Exists?
  if( file_exists($fullPath) ){
    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    // Determine Content Type
    switch ($ext) {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename='"".basename($fullPath)."'";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );
  } else
    die('File Not Found');
}
?>

在上面的例子中,您需要对其进行修改,以便只传递回您所拥有的数据,上面的例子是针对文件(来自您的例子,如/tmp)

由于您当前正在保存一个临时文件作为过程的一部分,我认为您正在做的是从数据库中读取BLOB,对吗?没有从数据库中保存的链接加载文件?

在这种情况下,我猜您将BLOB放入一个变量中,并使用file_put_contents()将其保存到tmp目录中。然后readfile()将其发送到浏览器?

如果是这种情况,那么您实际上可以完全跳过文件写入,只需将BLOB直接echo发送到浏览器。

您只需要事先发送适当的标题即可。使用header("Content-disposition: attachment; filename: something.ext");就足够下载了。你也可以发送文件的MIME类型,例如。header("Content-type: application/pdf");

您还必须记住,某些文件类型默认情况下是在浏览器中打开的。因此,如果你发送一个pdf MIME类型的标题,而不发送内容处理标题,用户将在浏览器中看到pdf,而不是被提示下载。

编辑:只是放一个完整的例子,假设你使用的是mysql

$results = mysql_query($query);
while($row = mysql_fetch_array($results)) {
  $fileContent = $row['file'];
  $filename = $row['name']
  /* Get MIME type assuming that has 
     been saved with the file in the database
  */
  $mimeType = $row['type'];
}
// optional send mime type header
header("Content-type: $mimeType");
header("Content-disposition: attachment; filename = $filename");
echo $fileContent;