下载流程
- resp.setHeader("Content-Disposition", "attachment;filename="+filesName);(setHeader详解)
- 创建输入流(不要用getServletContext().getRealPath(path))原因
- 输出流
public class downL extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = "/WEB-INF/classes/img.png";
this.getServletContext().getRealPath(path)
String filesName = path.substring(path.lastIndexOf("/")+1);
resp.setHeader("Content-Disposition", "attachment;filename="+filesName);
InputStream in = this.getServletContext().getResourceAsStream(path);
int len = 0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while ((len = in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}