繁体   English   中英

使html文件可下载

[英]To make html file downloadable

我有一个html文件"sample.html"我需要通过单击页面中的按钮使用户下载此文件。

如何使用php使HTML文件可下载

简而言之,您需要读取文件,设置正确的标题并回显文件。

header('Content-disposition: attachment; filename=' . $file_name);
header('Content-type: ' . $file_mime);
$file_content = file_get_contents($file_location);
echo $file_content;

将按钮链接到PHP文件,然后瞧。

<?php

$output_file = "example_name.html";

header('Pragma: no-cache"');
header('Expires: 0'); 
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header('Content-Transfer-Encoding: none');

//This should work for IE & Opera
header('Content-Type: application/octetstream; name="' . $output_file . '"');
//This should work for the rest
header('Content-Type: application/octet-stream; name="' . $output_file . '"');

header('Content-Disposition: inline; filename="' . $output_file . '"');

include "your_html_file.html";

exit();

?>

您可以使用document.documentElement.outerHTML获取页面的HTML源,然后使用FileSystemObject(或其他等效的api)将其保存到磁盘。 您将需要低安全性设置,以使其在没有提示的情况下起作用。

这是一个简单的Java脚本(特定于IE):

function SaveToDisk(sPath)
{
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fileDest = fso.CreateTextFile(sPath, true);
    if (fileDest)
    {
       fileDest.Write(document.documentElement.outerHTML);
       fileDest.close();
    }

}

您可以创建一个这样的页面

// definisco una variabile con il percorso alla cartella
// in cui sono archiviati i file
$dir = "/root/www/download/";

// Recupero il nome del file dalla querystring
// e lo accodo al percorso della cartella del download
$file = $dir . $_GET['filename'];

// verifico che il file esista
if(!file)
{
  // se non esiste chiudo e stampo un errore
  die("Il file non esiste!");
}else{
  // Se il file esiste...
  // Imposto gli header della pagina per forzare il download del file
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename= " . $file);
  header("Content-Transfer-Encoding: binary");
  // Leggo il contenuto del file
  readfile($file);
}

然后您可以通过传递文件名来调用它

force-download.php?filename=sample.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM