/**
* 下载文件
*?
* @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);
}
}