zoukankan      html  css  js  c++  java
  • commons-fileupload实现文件上传下载

    commons-fileupload是Apache提供的一个实现文件上传下载的简单,有效途径,需要commons-io包的支持,本文是一个简单的示例

    上传页面,注意设置响应头

    <body>
        <center>
        <h1>文件上传页面</h1><hr>
        <form action="${pageContext.request.contextPath }/servlet/UploadServlet" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file1"/><br>
        描述信息:<textarea rows="5" cols="45" name="discription"></textarea><br>
        <input type="submit" value="上传"/>
        </form>
        </center>
      </body>

    上传的servlet

    //上传文件
            String upload=this.getServletContext().getRealPath("WEB-INF/upload");
    
            String temp=this.getServletContext().getRealPath("WEB-INF/temp");
    
            Map pmap=new HashMap();
            //get client IP address
            pmap.put("ip", request.getRemoteAddr());
    
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //设定内存缓冲区大小 Set the memory buffer size
            factory.setSizeThreshold(1024*100);
            //指定临时文件目录 Specifies the directory for temporary files
            factory.setRepository(new File(temp));
    
    
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("utf-8");
            fileUpload.setFileSizeMax(1024*1024*100);
            fileUpload.setSizeMax(1024*1024*200);
    
            //set form style enctype="multipart/form-data"
            if(!fileUpload.isMultipartContent(request))
            {
                throw new RuntimeException("请使用正确的表单进行上传");
            }
    
            //解析request
            try {
                List<FileItem> list= fileUpload.parseRequest(request);
    
                //遍历list
                for(FileItem item:list)
                {
                    if(item.isFormField())
                    {
                        String name=item.getFieldName();
                        String value=item.getString("utf-8");
    
                        pmap.put(name, value);
                    }else
                    {
                        String realname=item.getName();
                        String arry[]=realname.split("\\");
                        realname=arry[arry.length-1];
                        System.out.println(realname);
                        String uuidName=UUID.randomUUID().toString()+"_"+realname;
    
                        pmap.put("realname", realname);
                        pmap.put("uuidname", uuidName);
    
                        InputStream in=item.getInputStream();
                        String hash=Integer.toHexString(uuidName.hashCode());
                        String savepath="/WEB-INF/upload";
                        for(char c:hash.toCharArray())
                        {
                            upload+="/"+c;
                            savepath+="/"+c;
                        }
                        new File(upload).mkdirs();
                        pmap.put("savepath", savepath);
                        OutputStream out=new FileOutputStream(new File(upload,uuidName));
                        IOUtils.In2Out(in, out);
                        IOUtils.close(in, out);
    
                        item.delete();
                    }
                }
    
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
    
            //向数据库中插入数据
    
            Resourse r=new Resourse(); 
            try {
                BeanUtils.populate(r, pmap);
                String sql="insert into netdisk values(null,?,?,?,?,null,?)";
                QueryRunner runner=new QueryRunner(DaoUtils.getSource());
                runner.update(sql,r.getUuidname(),r.getRealname(),r.getSavepath(),r.getIp(),r.getDescription());
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } 
    
            //重定向回主页
            response.sendRedirect(request.getContextPath()+"/index.jsp");

    为防止重名,所以使用了UUIDNAME,把文件上传到web-inf/upload文件夹下,并且将路径与文件名保存到数据库中,上传功能完成

    下载实现

    下载页面

    <body>
        <center>
        <h1>下载列表</h1><hr>
        <c:forEach items="${requestScope.list }" var="r">
            <h2>文件名:${r.realname }<br></h2>
            上传时间:${r.uploadtime }<br>
            上传者IP:${r.ip }<br>
            描述信息:${r.description }<br>
            <a href="${pageContext.request.contextPath }/servlet/DownServlet?id=${r.id}">下载</a><br><hr>
        </c:forEach>
        </center>
      </body>

    下载实现

      response.setContentType("text/html;charset=utf-8");
              //获取ID
            String id=request.getParameter("id");
            //根据ID查找资源
            String sql="select * from netdisk where id=?";
            Resourse r=null;
            QueryRunner runner=new QueryRunner(DaoUtils.getSource());
            try {
                 r= runner.query(sql, new BeanHandler<Resourse>(Resourse.class), id);
            } catch (SQLException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
    
            if(r==null)
            {
                response.getWriter().write("找不到该资源!!!!");
                return;
            }else
            {
                //指定响应头
                response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(r.getRealname(),"UTF-8"));
                response.setContentType(this.getServletContext().getMimeType(r.getRealname()));
                String filePath=this.getServletContext().getRealPath(r.getSavepath()+"/"+r.getUuidname());
                InputStream in=new FileInputStream(filePath);
                OutputStream out=response.getOutputStream();
                IOUtils.In2Out(in, out);
                IOUtils.close(in, null);
            }

    上传下载完成,注意,下载时一定要指定两个响应头

    IO工具类

    public class IOUtils {
        private IOUtils() {
        }
    
        public static void In2Out(InputStream in,OutputStream out) throws IOException{
            byte [] bs = new byte[1024];
            int i = 0;
            while((i=in.read(bs))!=-1){
                out.write(bs,0,i);
            }
        }
    
        public static void close(InputStream in,OutputStream out){
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    in = null;
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    out = null;
                }
            }
        }
    }

    完成

  • 相关阅读:
    php发送post请求的方法
    跨域请求的三种解决办法
    php验证码+js点击刷新
    13.mysql数据类型
    12.dateformat常用格式
    11.设计的三大范式
    nginx passwd (http://www.voidcn.com/article/p-suebfyqy-nx.html)
    删除文件 过滤某个文件
    mac必装软件
    elasticsearch 安装
  • 原文地址:https://www.cnblogs.com/jjx2013/p/6223745.html
Copyright © 2011-2022 走看看