1 request.setCharacterEncoding("utf-8"); 2 String name=request.getParameter("name"); 3 //1、设置响应头 4 response.setContentType("application/force-download"); 5 //2、读取文件 6 String path=getServletContext().getRealPath("/file/"+name); 7 InputStream in=new FileInputStream(path); 8 //3、对文件名进行编码 9 name=URLEncoder.encode(name, "utf-8"); 10 //4、设置响应头 11 response.setHeader("Content-Disposition","attachment;filename="+name);//如果不写attachment,则会在浏览器中打开 12 response.setContentLength(in.available()); 13 //5、开始copy文件 14 OutputStream out=response.getOutputStream(); 15 byte[] b=new byte[1024]; 16 int len=-1; 17 while((len=in.read(b))!=-1) 18 { 19 out.write(b, 0, len); 20 } 21 out.close(); 22 in.close(); 23 24 25 }
写在Servlet中,可以防止盗链,进行过滤等操作
转载于:https://www.cnblogs.com/liuwt365/p/4158225.html
最后
以上就是鲤鱼衬衫最近收集整理的关于Java下载Servlet Demo的全部内容,更多相关Java下载Servlet内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复