java 文件download简易工程

来源:互联网 发布:linux下复制粘贴命令 编辑:程序博客网 时间:2024/05/21 20:17
public class servlet extends HttpServlet{private ServletConfig servletConfig;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//bianli(req, resp);// TODO Auto-generated method stub//resp.getOutputStream().write("你好".getBytes());//String usernameString=req.getParameter("username");//resp.getOutputStream().write(usernameString.getBytes());bianli(req, resp);//super.doGet(req, resp);//int a=0;//a++;//String method=req.getMethod();//String aString=servletConfig.getInitParameter("data");//resp.getOutputStream().write(Integer.toString(a).getBytes());//resp.getOutputStream().write(aString.getBytes());}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubdoGet(req, resp);}@Overridepublic void init(ServletConfig config) throws ServletException {// TODO Auto-generated method stub//super.init();this.servletConfig=config;}public void bianli(HttpServletRequest req, HttpServletResponse resp){//File file=new File("D:"+File.separator+"test");File file=new File("D:");File[]files=file.listFiles();/*try {resp.getOutputStream().write(files[1].getName().getBytes());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/boolean youmeiyou=false;String usernameString=req.getParameter("username");for (int i = 0; i < files.length; i++) {if (files[i].getName().contains(usernameString)) {youmeiyou=true;InputStream in=null;OutputStream outputStream=null;int len=0;byte[]b=new byte[1024];resp.setHeader("content-disposition", "attachment;filename="+files[i].getName());try {outputStream=resp.getOutputStream();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}try {in=new FileInputStream(files[i]);while ((len=in.read(b))>0) {outputStream.write(b,0,len);}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return;}/*if(!files[i].getName().contains(usernameString)){try {resp.getOutputStream().write("你搜索的文件不存在".getBytes());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}*/}if (youmeiyou==false) {try {resp.getOutputStream().write("你搜索的文件不存在".getBytes());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

0 0