html中使用a标签的href属性链接到资源路径和url-pattern再加上?key=value
<h1>打开文件,href传输的路径是直接写资源路径的文件路径即可</h1>
<a href="/s5/downloadResource/wolf.jpg">点击会直接打开图片</a>
<a href="/s5/downloadResource/a.txt">直接打开文本文件</a>
<hr/>
<h1>下载文件,href传输的路径是Servlet资源路径加?加key和value</h1>
<a href="/s5/download?filename=wolf.jpg">下载图片</a>
<a href="/s5/download?filename=a.txt">下载文本</a>
服务端Servlet:文件下载案例的分析:
- 获取请求参数,getParameter()根据参数名获取参数值
- 获取getServletContext对象,用getServletContext对象的getRealpath()找到真实路径,再用字节输入流输入到内存
- 设置响应头的content-type为filename(filename是什么类型需要getMimeType去获取)
- 设置响应头的content-disposition为attachment附件打开
@WebServlet("/download")
public class DownloadServletTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取请求参数,文件名称
String filename = request.getParameter("filename");
// 2.找到真实路径,使用字节输入流输入到内存
ServletContext servletContext = request.getServletContext();
String realPath = servletContext.getRealPath("/downlaodResource/" + filename); //+ filename动态的获取文件名,实现点拿个下载哪个
FileInputStream fis = new FileInputStream(realPath);
// 3. 设置响应头的content-type为filename(filename是什么类型需要getMimeType去获取)
String mime = servletContext.getMimeType(filename);
response.setHeader("content-type","mime");
// 4. 设置响应头的content-disposition为attachment附件打开
response.setHeader("content-disposition","attachment;filename"+filename);
// 5.将输入流的数据写出到输出流中,完成对拷
ServletOutputStream os = response.getOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
os.write(buff,0,len);
}
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}