java 文件下载 中文名称乱码 解决

 

调用例子:FileUtils.downFile(request, response, filePath, "application/x-msdownload;");

FileUtils.downFile_2(request, response, filePath, "application/x-msdownload;");

 

/**

* 下载文件

* @param filePath

*            源文件路径

* @param contentType

*            文件类型

* @param request

* @param response

* @throws IOException

*/

public static void downFile(

HttpServletRequest request,

HttpServletResponse response,

String filePath,

String contentType) throws IOException

{

File file = new File(filePath);

if (file.exists()) {

String fileName = file.getName();

byte[] bytes = FileUtils.readFileToByteArray(file);

// response.setContentType("application/x-download");

response.setContentType(contentType);

String agent = request.getHeader("USER-AGENT");// 用户代理

// 防止中文文件名乱码

if (null != agent && -1 != agent.indexOf("MSIE")) {

String codedfilename = StringUtils.replace(URLEncoder.encode(fileName, "UTF-8"), "+", "%20");

response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);

} else if (null != agent && -1 != agent.indexOf("Mozilla")) {

String codedfilename = MimeUtility.encodeText(fileName, "UTF-8", "B");

response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);

} else {

response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

}

response.setContentLength(bytes.length);

response.getOutputStream().write(bytes);

}

}

 

public static void downFile_2(

HttpServletRequest request,

HttpServletResponse response,

String filePath,

String contentType) throws IOException {

File file = new File(filePath);

if (file.exists()) {

String fileName = file.getName();

byte[] bytes = FileUtils.readFileToByteArray(file);

// response.setContentType("application/x-download");

response.setContentType(contentType);

String agent = request.getHeader("USER-AGENT");// 用户代理

// 防止中文文件名乱码

if (null != agent && -1 != agent.indexOf("MSIE")) {

String codedfilename = StringUtils.replace(URLEncoder.encode(fileName, "UTF-8"), "+", "%20");

response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);

}

// else if (null != agent && -1 != agent.indexOf("Mozilla")) {

// String codedfilename = MimeUtility.encodeText(fileName, "UTF-8", "B");

// response.setHeader("Content-Disposition", "attachment;filename=" + downFile_2);

// }

else {

fileName = new String(file.getName().getBytes(), "ISO8859-1");

response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

}

response.setContentLength(bytes.length);

response.getOutputStream().write(bytes);

}

}

猜你喜欢

转载自vernonchen163.iteye.com/blog/1934739