上篇文章解决了IE8下fileupload上传的问题,这篇文章写的是下载文件 文件名称乱码问题。 从网上找了 一些资料解决了乱码 具体代码如下:
@RequestMapping("/download")
public ModelAndView download(HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String fileId = request.getParameter("fileId");
AttachmentBean attachment = attachmentService.getAttachmentById(fileId);
Properties _props = ReadPropertiesUtil.props("uploadfile.properties");
String curProjectPath = request.getSession().getServletContext().getRealPath("/");
// String curProjectPath = _props.get("filePath").toString();
String downLoadPath = curProjectPath +"/" + uploadFolderName;
System.out.println(downLoadPath);
try {
File file = new File(downLoadPath+"/"+attachment.getFileName());
if(file.exists()){
long fileLength = file.length();
// response.setContentType("application/x-msdownload;");
response.setContentType("application/octet-stream; charset=utf-8");
// response.setHeader("Content-disposition", "attachment; filename="
// + new String(attachment.getFileName().getBytes("utf-8"), "utf-8"));
response.setHeader("Content-disposition", "attachment;"+ encodeFileName(request,attachment.getFileName()));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(file));
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);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
public static String encodeFileName(HttpServletRequest request, String fileName) {
String userAgent = request.getHeader("User-Agent");
String rtn = "";
try {
String new_filename = URLEncoder.encode(fileName, "UTF8");
// 如果没有UA,则默认使用IE的方式进行编码,因为毕竟IE还是占多数的
rtn = "filename=\"" + new_filename + "\"";
if (userAgent != null) {
userAgent = userAgent.toLowerCase();
// IE浏览器,只能采用URLEncoder编码
if (userAgent.indexOf("msie") != -1) {
rtn = "filename=\"" + new_filename + "\"";
}
// Opera浏览器只能采用filename*
else if (userAgent.indexOf("opera") != -1) {
rtn = "filename*=UTF-8''" + new_filename;
}
// Safari浏览器,只能采用ISO编码的中文输出
else if (userAgent.indexOf("safari") != -1) {
rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
}
// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
else if (userAgent.indexOf("applewebkit") != -1) {
new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");
rtn = "filename=\"" + new_filename + "\"";
}
// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
else if (userAgent.indexOf("mozilla") != -1) {
rtn = "filename*=UTF-8''" + new_filename;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return rtn;
}
上面的代码解决多个浏览的乱码问题 目前包括IE8、Firefox、谷歌浏览器一些主流浏览器。