今天遇到一个奇葩需求,文件后缀名是中文的.
例子:文件名.后缀名
文件名不会乱码,但是后缀名会乱码,求大神指点..
后台是java的.
而且就ie8不行,使用其他浏览器,以及高版本ie显示正常.
@RequestMapping("/download")
public HttpServletResponse download(String fileName, HttpServletRequest request,
HttpServletResponse response,String fileUrl) throws Exception {
try {
//获得文件
File file = new File(fileUrl);
//获取文件名
fileName = URLDecoder.decode(fileName,"utf-8");
//获得文件后缀名
String ext = fileName.substring(fileName.indexOf(".")+1).toUpperCase();
//以流的形式下载文件
InputStream is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
//设置response header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
调试一下看看代码中与文件名相关的变量的值是否正确?
如果正确,可能是某些函数对文件名编码的要求。
就是低版本的IE浏览器的问题了,你的Java代码已经正确处理编码了,没有问题的。而且现在大家都是用高版本浏览器的。
try {
String path = file.getPath();
String fileName = file.getName();
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// attchment改成inline,在浏览器中打开
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859_1"));
// 设置返回的文件类型
response.addHeader("Content-Length", "" + file.length());
// 得到向客户端输出二进制数据的对象
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/x-msdownload");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception ex) {
ex.printStackTrace();
}
ext = URLDecoder.decode(ext ,"utf-8");