rar文件 点击后自动在网页中打开
jsp+tomcat5.5
页面中提供rar文件和jad文件下载,结果jad文件左键点击后会弹出下载框,rar文件点击后会在页面中打开rar文件(跟用记事本强行打开一样,一堆乱七八糟的字符),请问这是什么原因?
HTML code
<!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>无标题文档</title>
</head>
<body>
<center>
<p><a href="#">首页</a><a href="#">帮助</a><a href="#">关于</a>
</p>
<p>Test</p>
<p> 下载手机客户端<a href="test.jad">test.jad</a></p>
<p>下载压缩包<a href="test.rar">test.rar</a></p>
</center>
</body>
</html>
------解决方案--------------------用下面这个方法下载吧,很严谨
if (!new File(sName).exists())//sName是点击下载时传过来的参数(文件名)
{
//文件不存在
request.getRequestDispatcher("跳回原来页面").forward(request,response);
}else
{
out.clear();
out = pageContext.pushBody();
try
{
sName = new String(sName.getBytes("iso8859-1"), "gb2312");
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment; filename="+ new String(name.getBytes("gb2312"),"iso8859-1"));//转码,不会出现乱码
bis = new BufferedInputStream(new FileInputStream(sName));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
response.flushBuffer();
}
catch (Exception e)
{
String simplename = e.getClass().getSimpleName();
if(!"Client
AbortException".equals(simplename)){
e.printStackTrace();
}
}
finally
{
if (bis != null)
{
bis.close();
}
if (bos != null)
{
bos.close();
}
}
}
------解决方案--------------------
web.xml文件中配置mime下载文件类型
TOMCAT在默认情况下下载.rar的文件是把文件当作text打开,以至于IE打开RAR文件为乱码,如果遇到这种情况时不必认为是浏览器的问题,大多数浏览器应该不会死皮赖脸地把二进制文件当作文本打开,一般都是服务器给什么浏览器就开什么.解决方法: 打开conf/web.xml,加入下面的代码. <mime-mapping><extension>doc</extension><mime-type>application/msword</mime-type></mime-mapping><mime-mapping><extension>xls</extension><mime-type>application/msexcel</mime-type></mime-mapping><mime-mapping><extension>pdf</extension><mime-type>application/pdf</mime-type></mime-mapping><mime-mapping><extension>zip</extension><mime-type>application/zip</mime-type></mime-mapping><mime-mapping><extension>rar</extension><mime-type>application/rar</mime-type></mime-mapping><mime-mapping><extension>txt</extension><mime-type>application/txt</mime-type></mime-mapping><mime-mapping><extension>chm</extension><mime-type>application/mshelp</mime-type></mime-mapping> 重启TOMCAT,清除IE缓存,再打开RAR的文件时就可以正常下载了.