java文件下载
在开发中遇到需要下载文件的需求,现在把文件下载整理一下。
- 传统文件下载方式有超链接下载或者后台程序下载两种方式。通过超链接下载时,如果浏览器可以解析,那么就会直接打开,如果不能解析,就会弹出下载框;而后台程序下载就必须通过两个响应头和一个文件的输入流。
- 后台程序下载
- 两个响应头:
- Content-Type:其值有比如 text/html;charset=utf-8
- Content-Disposition:其值为 attachment;filename=文件名 以附件形式打开
- 流:需要获取文件的输入流,然后通过response对象的输出流输出到客户端。
- 两个响应头:
1.Spring-ResponseEntity响应json格式接口,进行下载文件
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
@RequestMapping(value = "/demoDown") //匹配的是href中的download请求
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,Model model) throws IOException {
String downloadFilePath = request.getSession().getServletContext().getRealPath("uploadbill");
filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
//新建一个文件
File file = new File(downloadFilePath + File.separator + filename);
//http头信息
HttpHeaders headers = new HttpHeaders();
//设置编码
String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", downloadFileName);
//MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
<!-- 上传组件包 上传时需要这两个依赖包,下载时可以不需要(如果以第一种方式进行下载文件则需要)-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.以流的方式下载
public HttpServletResponse download(String path, HttpServletResponse response) {
try {
// path指要下载的文件的路径。
File file = new File(path);
// 取得文件名
String filename = file.getName();
// 取得文件的后缀名
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 获取一个输入流
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()));
response.addHeader("Content-Length", "" + file.length());
// 设置内容类型
response.setContentType("application/octet-stream");
//获取输出流,然后写出到客户端
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
//强制写出
toClient.flush();
//关闭流
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
3.下载本地文件
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
//文件的默认保存名
String fileName = "Operator.doc".toString();
// 文件的存放路径
String filePath="c:/Operator.doc";
// 读到流中
InputStream inStream = new FileInputStream(filePath);
// 设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
try {
while ((len = inStream.read(b)) > 0){
response.getOutputStream().write(b, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
4.下载网络文件
public void downloadNet(HttpServletResponse response) throws MalformedURLException {
//网络地址
String urlPath="windine.blogdriver.com/logo.gif";
URL url = new URL(urlPath);
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif");
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
5.支持在线打开的方式
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset();
// 在线打开方式
if (isOnLine) {
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名应该编码成UTF-8
} else {
// 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0){
out.write(buf, 0, len);
}
br.close();
out.close();
}
注意事项:要进行文件下载操作,不能用ajax请求来下载文件。
6.参考博文
(1)https://www.cnblogs.com/lucas1024/p/9533220.html(java下载文件的几种方式)
(2)https://blog.csdn.net/tuesdayma/article/details/79506432(不能使用ajax请求来进行下载文件)
(3)https://blog.csdn.net/yqs_love/article/details/51959776(拒绝访问、找不到指定路径问题解决)
(4)https://blog.csdn.net/loophome/article/details/86006812(Spring-ResponseEntity响应json格式接口)
(5)https://blog.csdn.net/qq_36537546/article/details/88421680(File.separator 详解)