那項目拖了這麼久了……今天寫最後的“下載專區”。其中就不可避免的涉及到中文文件下載的問題。
我現在是在Windows下開發,文件路徑是GBK的編碼,而我的php文件用的是utf-8,所以會造成無法找到文件。但是如果每次都用mb_convert_encoding轉換成gbk的格式,可能會在Linux的服務器上有出現問題。所以應該考慮比較兼容的方式。
網上搜了一下,普遍是用的下面的代碼
<?php
$file = "/tmp/中文名.tar.gz";
$filename = basename($file);
header("Content-type: application/octet-stream");
//處理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = rawurlencode($filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
header("Content-Length: ". filesize($file));
readfile($file);
當然,測試並沒有效果。
然後我就用算是取巧的辦法。
$filename = '哈哈.doc';
$filePath = './Upload/file/'.$filename;
// 中文可能會出現問題
if(!file_exists($filePath)){
$filePath = mb_convert_encoding($filePath, "gbk", "utf-8");
$filename = mb_convert_encoding($filename, "gbk", "utf-8");
if(!file_exists($filePath)){
$this->error('沒有找到文件,請稍後再試……');
}
}
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Length: ". filesize($filePath));
readfile($filePath);
先判斷現在的utf-8編碼是否可行,如果不行,把文件路徑的字符串轉換成gbk格式,在判斷文件是否存在。
如果都不存在,則認爲文件就是不存在。
不知道我這想法有沒有錯誤呢?