Java下载Servlet Demo

 request.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
//1、设置响应头
response.setContentType("application/force-download");
//2、读取文件
String path=getServletContext().getRealPath("/file/"+name);
InputStream in=new FileInputStream(path);
//3、对文件名进行编码
name=URLEncoder.encode(name, "utf-8");
//4、设置响应头
response.setHeader("Content-Disposition","attachment;filename="+name);//如果不写attachment,则会在浏览器中打开
response.setContentLength(in.available());
//5、开始copy文件
OutputStream out=response.getOutputStream();
byte[] b=new byte[1024];
int len=-1;
while((len=in.read(b))!=-1)
{
out.write(b, 0, len);
}
out.close();
in.close(); }

写在Servlet中,可以防止盗链,进行过滤等操作

上一篇:mysql数据库的查询语句


下一篇:无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转换为类型“System.Collections.Generic.IList`1