大家好,我写了一个上传程序。文本文件上传之后再显示其内容。
上传过程没有问题,但在最后显示文本文件的内容时,中文内容出现乱码,英文就没有问题。
我想问下这是什么原因?需要怎么解决?谢谢大家!
代码如下:
首页代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload</title>
</head><body>
<p>Upload new news files.</p>
<form id="form1" name="form1" method="post" action="31.php" enctype="multipart/form-data">
  upload a file:
  <label>
  <input type="hidden" name="MAX_FILE_SIZE"  value="3000000"/>
  <input type="file" name="userfile" />
  </label> 
  <label>
  <input type="submit" name="Submit" value="Send" />
  </label>
</form><p>&nbsp; </p>
</body>
</html>上传代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload</title>
</head><body>
<?php
include ('conn.php');
?>
<?php
$userfile=$_FILES['userfile'];
switch ($userfile['error'])
{
case 1: echo 'File exceeded upload_max_filesize';
break;
case 2: echo 'File exceeded max_file_size';
break;
case 3: echo 'File only partially uploaded';
break;
case 4: echo 'No file uploaded';
break;
case 6: echo 'Cannot upload file:No temp directory specified';
break;
case 7: echo 'Upload failed:Cannot write to disk';
break;
}
if ($userfile['type'] !='text/plain')
{
echo 'Error, I am sorry that the file is not plain text.';
exit;
}
$upfile='./up/'.$userfile['name'];
if (is_uploaded_file($userfile['tmp_name']))
{  if (!move_uploaded_file($userfile['tmp_name'],$upfile))
   {
   echo 'Error,Could not move file to destination directory.';
   exit;
   } else
 echo 'File uploaded successfully';
 }
else
{
echo 'Error, No file is uploaded!';
exit;
}
$contents= file_get_contents($upfile);$contents=strip_tags($contents);
file_put_contents($userfile['name'],$contents);
echo '<p> Previes of uploaded file contents:<br/><hr/>';echo nl2br($contents);echo '<br/><hr/>';
$db->close();
   
?>
</body>
</html>
谢谢大家给予详细的指导!

解决方案 »

  1.   

    文件内容是utf-8编码的吗?你是用什么方式察看上传后的文件的?如果是浏览器查看,请确认浏览器的编码和文件内容是一样的。
      

  2.   

    是文件编码的问题
    要保证内容编码与页面编码一致
    现在页面是utf8的,如果上传utf8文件,查看应该没问题,如果上传gbk的文件,需要先转换成utf8再显示
      

  3.   

    header("cotent-Type:","text/html;charset=gb2312");
    看看IE 的编码是否正确