java学习之下载文件损坏问题的解决
2018-04-10 本文已影响22人
爱音乐的二狗子
刚学习java io的时候,没有注意到文件下载后文件损坏的问题,今天做项目碰到了,就顺便做个笔记吧!关键点看粗体字代码。
public void getWordFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
private static final String fileNameString = "XXXX.docx"; //声明要下载的文件名
//String fileName = new String(fileNameString.getBytes("ISO8859-1"), "UTF-8");
response.setContentType("application/octet-stream");
// URLEncoder.encode(fileNameString, "UTF-8") 下载文件名为中文的,文件名需要经过url编码
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNameString, "UTF-8"));
File file;
FileInputStream fileIn = null;
ServletOutputStream out = null;
try {
String contextPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
String filePathString = contextPath + "database" + File.separator + fileNameString;
file = new File(filePathString);
fileIn = new FileInputStream(file);
out = response.getOutputStream();
byte[] outputByte = new byte[1024];
int readTmp = 0;
while ((readTmp = fileIn.read(outputByte)) != -1) {
out.write(outputByte, 0, readTmp); //并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据的长度,否则会出现文件损坏的错误
}
}
catch (Exception e) {
log.error(e.getMessage());
}
finally {
fileIn.close();
out.flush();
out.close();
}
}
以上仅为个人工作、学习笔记。