java实现中文文件下载,解决乱码问题,亲测无问题~~

时间:2023-02-10 11:35:27


byte[] by=null;
try {
by = filename.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
filename = new String(by,"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(filename);

//解决中文文件名乱码问题
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器
response.reset();//如果有换行,对于文本文件没有什么问题,但是对于其它格
//式,比如AutoCAD、Word、Excel等文件下载下来的文件中就会多出一些换行符//0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。同//时response.reset()这种方式也能清空缓冲区, 防止页面中的空行等输出到下载内容里去
if(filename.length()>150)//解决IE 6.0 bug
filename=new String(filename.getBytes("GBK"),"ISO-8859-1");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.setHeader("Connection", "close");
ServletOutputStream sos = response.getOutputStream();
FileInputStream fis = null;
String filepath = path+filename;
File d = new File(filepath);
if (d.exists())
{
fis = new FileInputStream(filepath);//
byte b[] = new byte[1000];
int j;
while ((j = fis.read(b)) != -1)
{
try
{
sos.write(b, 0, j);
}
catch (IOException exp)
{
}
}
fis.close();
sos.flush();
sos.close();
}