[英]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.