HTTP下载文件名乱码解决方案

HTTP下载文件名乱码解决方案
由于目前国际字符编码还未真正意义上的统一,编码标准多元化,在日常处理文件上传下载的时候,造成我们在处理文件名的时候会不可避免的出现乱码的情况。针对这种情况,
我们想到了一种解决方案,特此拿出来和各位童鞋们分享一下。
先贴一段代码,此为文件下载的类。
class Trs_Utils_Downloader
{
private $file=null;
private $fileRealPath ="";
private $fileName = "";
private $fileExist =false;
private $readBytes = 0;
private $mode = "r";
public function __destruct()
{
if(null!==$this->file){
fclose($this->file);
}
}
/**
*
* @param $fileRealPath 文件的绝对路径
* @param $fileName 真实文件名
* @param $mode 文件的读写模式
* @param $readBytes 每次读入缓冲区的字节数,默认1024 bytes
*/
public function __construct($fileRealPath, $fileName, $mode, $readBytes=1024)
{
$this->fileRealPath = $fileRealPath;
$this->fileName = $fileName;
$this->readBytes = $readBytes;
$this->mode =$mode;
}
/**
* 处理文件下载
*/
public function dealWith()
{
if(file_exists($this->fileRealPath))//检查文件是否存在
{
$this->file= fopen($this->fileRealPath,$this->mode);//打开文件
//输入文件标签
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: " . filesize($this->fileRealPath));
if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE"))
{
header("Content-Disposition: attachment; filename=" . urlencode($this->fileName));
}
else{
header("Content-Disposition: attachment; filename=" . $this->fileName);
}
while (!feof($this->file))
{
$out = fread($this->file,$this->readBytes);
if(!get_magic_quotes_gpc())
{
echo $out;
}else
{
echo stripslashes($out);
}
}
}else{
echo "File not exist!";
}
}
}
大家看这一段代码
header("Content-Disposition: attachment; filename=" . $this->fileName);
刚开始我用火狐下载的时候,中文或者其他国家语言的文件名没出现乱码的情况,用IE下载的时候就出现问题了,显示的是乱码,其他的主流浏览器没有出现这种情况,唯有IE会出现这种情况。询问了一位朋友,给出这样的答复:IE是默认GBK编码写入磁盘文件,其他的浏览器默认以页面编码为基准,(火狐,苹果根据默认会是UTF-8)。
于是我将代码进行了改进:
if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE"))
{
header("Content-Disposition: attachment; filename=" . urlencode($this->fileName));
}
else{
header("Content-Disposition: attachment; filename=" . $this->fileName);
}
判断客户端使用的浏览器类型,如果是IE进行一次编码,就这样困扰的问题被解决了。

Need a translation service?

Please enter your personal details and we will contact you shortly

Words translated by CCJK

146,096,379

We are Certified

Our Client Satisfaction

rating for previous quarte

4.00

Over 95% of our clients recommend our language services to others

Copyright © CCJK Technologies Co., Ltd. 2000-2017. All rights reserved.
TOP