Response 文件下载
文件下载:页面显示超链接点击超链接后弹出下载提示框完成图片文件下载分析:超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求任何资源都必须弹出下载提示框使用响应头设置资源的打开方式:content-disposition: attachment ;filename=xxx步骤:1.定义页面,编辑超链接href属性,指向Servlet,传递资源名称fil
·
文件下载
- 页面显示超链接
- 点击超链接后弹出下载提示框
- 完成图片文件下载
分析
- 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求
- 任何资源都必须弹出下载提示框
- 使用响应头设置资源的打开方式:
content-disposition:attachment;filename=xxx
步骤
1.定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
2.定义Servlet
3.获取文件名称
4.使用字节输入流加载文件进内存
5.指定response的响应头 : content-disposition:attachment; filename=xxx
6.将数据写出到response输出流
download.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/downloadServlet?filename=1.jpg">图片1</a>
</body>
</html>
DownloadServlet
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取请求参数,文件名称
String filename = request.getParameter("filename");
//2.使用字节输入流加载文件进内存
//找到服务器的路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
//用字节流关联
FileInputStream fis = new FileInputStream(realPath);
//3,设置response响应头
//3.1设置响应头类型。content-type
String mimeType = servletContext.getMimeType(filename);//获取文件mime类型
response.setHeader("content-type",mimeType);
//3.2设置响应头打开方式content-disposition
response.setHeader("content-disposition","attachment;filename="+filename);
//4。将输入流的数据写出到输出流中
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024*8];
int len = 0 ;
while ((len = fis.read(buff)) != -1){
sos.write(buff,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)