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中,可以防止盗链,进行过滤等操作
时间: 2024-10-28 22:08:27