文件下载及乱码处理
/**
* 文件下载
* @param path
* @param fileName
* @param response
*/
public static void download(String path, String fileName, HttpServletResponse response){
File file=new File(path);
if(!file.exists()){
throw new AppException("文件不存在");
}else{
response.setContentType("application/force-download");
try {
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
throw new AppException("系统异常");
} finally {
try {
os.close();
bis.close();
fis.close();
} catch (Exception e) {
throw new AppException("系统异常");
}
}
}
}
中文乱码处理的关键:response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));