1、直接添加文件鏈接
<button>
<a href = "http://localhost/down.zip">
下載文件
</button>
2、傳遞參數查找並跳轉到下載鏈接
傳遞參數:
<button>
<a href = "http://localhost?f='down'">
下載文件
</button>
查找文件並跳轉到下載鏈接:
<?php
$down = $_GET['f']; //獲取文件參數
$filename = $down.'.zip'; //獲取文件名稱
$dir ="down/"; //相對於網站根目錄的下載目錄路徑
$down_host = $_SERVER['HTTP_HOST'].'/'; //當前域名
//判斷如果文件存在,則跳轉到下載路徑
if(file_exists(__DIR__.'/'.$dir.$filename)){
header('location:http://'.$down_host.$dir.$filename);
}else{
header('HTTP/1.1 404 Not Found');
}
結果:
文件存在,提示下載
文件不存在,跳轉404
3、head() 和 fread()函數把文件直接輸出到瀏覽器
<?php
$file_name = "down";
$file_name = "down.zip"; //下載文件名
$file_dir = "./down/"; //下載文件存放目錄
//檢查文件是否存在
if (! file_exists ( $file_dir . $file_name )) {
header('HTTP/1.1 404 NOT FOUND');
} else {
//以只讀和二進制模式打開文件
$file = fopen ( $file_dir . $file_name, "rb" );
//告訴瀏覽器這是一個文件流格式的文件
Header ( "Content-type: application/octet-stream" );
//請求范圍的度量單位
Header ( "Accept-Ranges: bytes" );
//Content-Length是指定包含於請求或響應中數據的字節長度
Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );
//用來告訴瀏覽器,文件是可以當做附件被下載,下載后的文件名稱為$file_name該變量的值。
Header ( "Content-Disposition: attachment; filename=" . $file_name );
//讀取文件內容並直接輸出到瀏覽器
echo fread ( $file, filesize ( $file_dir . $file_name ) );
fclose ( $file );
exit ();
}
結果:和第二個一樣
————————————————
版權聲明:本文為CSDN博主「change_any_time」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/change_any_time/java/article/details/79706772