链接:https://www.jianshu.com/p/f4016e2e1158
https://blog.csdn.net/xinyuebaihe/article/details/88249561
文件下载后文件损坏的问题,今天做项目碰到了,就顺便做个笔记吧!
本地文件下载:
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();
}
}
网络文件下载
https://blog.csdn.net/xiansu5452/article/details/79485388
public static boolean downloadFile(String fileUrl, String fileLocal) throws Exception {
boolean flag = false;
URL url = new URL(fileUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(6000);
urlCon.setReadTimeout(6000);
int code = urlCon.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
//读文件流
DataInputStream in = new DataInputStream(urlCon.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
byte[] buffer = new byte[2048];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
flag = true;
return flag;
}