@WebServlet(urlPatterns = "/fileDownload")
public class FileDownload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 文件下载:
* 以字节流的方式读取文件,给客户端响应回去
* 指导浏览器:回写的是一个附件,不要打开,可以下载
* 设置响应头:response.setHeader("Content-Disposition","attachment;filename="文件名"")
*
*
* 如果要设置下载的文件名:
* String agent = request.getHeader("User-Agent");
String filename="美女.jpg";
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
System.out.println(filename);
response.setHeader("Content-Disposition","attachment;filename"+filename);
*
*
* */
//指导浏览器回写的是一个附件,不要直接 打开,可以下载
response.setHeader("Content-Disposition","attachment;filename=a.jpg");
//一读一写复制文件
//得到文件绝对路径
String path = getServletContext().getRealPath("download/a.jpg");
System.out.println(path);
//获取本地输入流以及网络输出流
FileInputStream fis = new FileInputStream(new File(path));
ServletOutputStream os = response.getOutputStream();
//复制文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len=fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
//释放资源
fis.close();
}
}
Servlet之文件下载案例
最新推荐文章于 2021-12-11 10:52:55 发布