Servlet文件下载实现
Servlet文件下载实现
思路
下载文件的前提:我们需要一个文件(二进制IO流)和下载后的文件名
此时,我们知道使用resp可以向浏览器输出打印流(resp.getWriter().print())
那么我们让resp向浏览器输出二进制流就行了
获取OutputStream对象
ServletOutputStream os = resp.getOutputStream();
设置能支持浏览器下载的头信息: resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
代码实现
package com.base.index01;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取文件的绝对地址
String realPath = "D:\\MYcode_K\\Servlet_K\\Demo1\\response\\src\\main\\resources\\1.png";
// 通过切割字符串获取文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 设置能支持浏览器下载的头信息
resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
// 获取下载文件的文件流
FileInputStream is = new FileInputStream(realPath);
// 获取OutputStream对象
ServletOutputStream os = resp.getOutputStream();
// 创建缓冲区
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
// 读写操作
int len = 0;
byte[] bytes = new byte[1024];
while ((len = bufferedInputStream.read(bytes)) > 0) {
bufferedOutputStream.write(bytes,0,len);
}
// 释放资源
bufferedOutputStream.close();
bufferedInputStream.close();
os.close();
is.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}