1.创建Servlet类继承HttpServlet类
/**
* 文件下载
*
*/
@WebServlet("/test13")
public class ServletTest13 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//读取文件真实路径
String realPath = getServletContext().getRealPath("/img/login.ico");
//1.创建字节输入流,读取文件
FileInputStream is = new FileInputStream(realPath);
//2.设置响应头支持的类型
response.setHeader("Content-Type","application/octet-stream");
//3.设置响应头以下载方式打开附件
response.setHeader("Content-Disposition","attachment;filename=login.ico");
//4.获取字节输出流
ServletOutputStream os = response.getOutputStream();
//5.循环读写
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes))!=-1){
os.write(bytes,0,len);
}
//6.释放资源
is.close();
}
}
2.访问服务器,服务器处理逻辑后,向浏览器输出文件。
3.浏览器端显示下载后的附件。