黑马程序员技术交流社区

标题: 下载案例 [打印本页]

作者: 唯有不同    时间: 2019-3-14 14:03
标题: 下载案例
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter("filename");
ServletContext context = request.getServletContext();
String realPath = context.getRealPath("/img/"+filename);

FileInputStream fis = new FileInputStream(realPath);
String mimeType = context.getMimeType(filename);
response.setHeader("content-type",mimeType);
response.setHeader("content-disposition","attachment;filename="+filename);

ServletOutputStream sos = response.getOutputStream();
int len=0 ;
byte[] bytes = new byte[1024];
while ((len = fis.read())!=-1){
sos.write(bytes,0,len);
}
fis.close();
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2