有一段路徑是類似這樣的:

\\127.0.0.1\test\測試文件.doc

試著這樣要開檔案。

<?php
if (!file_exists($file_path)) {           
    // 伺服器檔案讀取錯誤       
    return;
}
readfile($file_path);

英文檔名可以成功,但遇到中文檔名就失敗了。稍微搜尋了一下,在《PHP中file_exists()函数不支持中文文件名解决办法》這篇文章看到載入檔案時要將檔名轉碼的概念,試著改寫如下。

$file_path = mb_convert_encoding($file_path,"UTF-8","big5");

較完整的線上讀取檔案、並送出合適檔頭強制瀏覽器下載檔案的程式碼片段如下:

<?php
// get filename
$file_path $row["file_raw_path"];
// 須轉碼,才能正確取得中文檔名資料
$file_path mb_convert_encoding($file_path'UTF-8''big5');
if(!file_exists($file_path)){
    // 伺服器檔案讀取錯誤
    return;
}
$file_size=filesize($file_path);

ob_end_clean();
header('Pragma: no-cache');
header('Expires: 0');
header('Last-Modified: '.gmdate('D, d M Y H:i ').' GMT');
header('Content-Type: '.$file_mime);
header('Content-Length: '.$file_size);
header('Content-Disposition: attachment; filename="'.$file_name.'";');
header('Content-Transfer-Encoding: binary');
readfile($file_path);
?>


It works.

 

arrow
arrow

    小攻城師 發表在 痞客邦 留言(0) 人氣()