文件下载工具类

时间:2021-05-16 19:57:57

有些文件下载会直接下载,当有些文件是pdf,txt之类的文件,可以支持在线打开。或者直接使用方法openOnlineDownload也可实现能在线打开的打开,不能打开的直接下载。

public class DownloadUtil {
/**
* 下载文件,需要返回的response,文件名,文件路径
* @param filename 文件名,会做中文乱码处理
* @param path 文件路径
* @param response
*/

public static HttpServletResponse downloadFile(String filename, String path,HttpServletResponse response) {
try {
File file = new File(path);
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(), "ISO-8859-1") );
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
/**
* 下载支持在线打开
* @param filePath
* @param response
* @param isOnLine
* @throws Exception
*/

public static HttpServletResponse openOnlineDownload(String filename,String path, HttpServletResponse response, boolean isOnLine) throws Exception {
File file = new File(path);
if (!file.exists()) {
response.sendError(404, "File not found!");
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + path);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + new String(filename.getBytes(), "ISO-8859-1"));
// 文件名应该编码成UTF-8
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
return response;
}
}