栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JvaWeb-文件上传、文件下载、FileItem的常用方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JvaWeb-文件上传、文件下载、FileItem的常用方法

文件上传 1.导入jar包

2.FileItem常用方法
System.out.println(
"name"+item.getFieldName()+
"文件名"+item.getName()
+"数据大小"+item.getSize()
+"文件类型"+item.getContentType()
+"是不是文本表单项"+item.isFormField()
);
3.上传文件

由于我们的表单包含文件表单项,所以我们不能再通过文本方式来提交参数,而应该用二进制的方式(

,而服务器端也不再使用req,getParamter来得到参数,而是通过ServletFileUpload类的parseRequest来返回参数集合(list),通过遍历这个集合判断哪些参数是文件表单项,对其进行条件筛选,将符合条件的表单项写入服务器的合适位置,若不是文件表单项,则调用getFiledName来判断该用哪个参数接收,则调用getString(“utf-8”)将其转化为字符串

//设置参数为utf-8
req.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();  //工厂类
ServletFileUpload upload = new ServletFileUpload(factory);  //上传文件类
Employee employee = null;
try {
            //获得参数列表
            List list = upload.parseRequest(req);
            String filename = null;
            String filepath=null;
            String ename = null;
            String pwd = null;
            String sex = null;
            String[]  hobbies=null;
            String hb = null;
            String birth = null;
            Date date = null;
            String phone = null;
            String remark =null;
            for(FileItem item:list){
                //若该表单项为文件表单项,则上传到服务器的文件夹中
                if(!item.isFormField()){
                    String type = item.getName().substring(item.getName().lastIndexOf('.'));
                    if(!(".jpg".equals(type) || ".png".equals(type) || ".gif".equals(type))){
                        resp.sendRedirect(req.getContextPath()+"/saveUser.html");
                        System.out.println(type+"文件类型不匹配");
                        return ;
                    }
                    if(item.getSize()>1024*100){
                        resp.sendRedirect(req.getContextPath()+"/saveUser.html");
                        System.out.println("文件过大");
                        return ;
                    }
                    String uuid = UUID.randomUUID().toString();

                     filename = uuid+type;
                     filepath = req.getServletContext().getRealPath("img");
                     File file = new File(filepath);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    item.write(new File(file,filename));
                }else{

                    if("ename".equals(item.getFieldName())){
                        ename = item.getString("utf-8");
                    }
                    if("pwd".equals(item.getFieldName())){
                        pwd = item.getString("utf-8");
                    }
                    if("sex".equals(item.getFieldName())){
                        sex = item.getString("utf-8");
                    }
                    if("hobby".equals(item.getFieldName())){
                        hb = item.getString("utf-8");
                        System.out.println("hb:"+hb);
                    }
                    if("birth".equals(item.getFieldName())){
                        date = Date.valueOf(item.getString("utf-8"));
                    }
                    if("phone".equals(item.getFieldName())){
                        phone = item.getString("utf-8");
                    }
                    if("remark".equals(item.getFieldName())){
                        remark = item.getString("utf-8");
                    }
                }
                employee = new Employee(null,ename,pwd,sex,hb,date,phone,remark,filename,filepath);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        EmployeeService service = new EmployeeServiceImpl();
        int res = service.addEmp(employee);
        if(res > 0){
            empList(req,resp);
        }else{
            req.setAttribute("msg","添加用户失败");
            req.getRequestDispatcher("/saveUser.html").forward(req,resp);
        }
文件下载
		//[1]从服务器中把需要下载的文件读取过来
        String realPath = req.getServletContext().getRealPath("/imgs");
        //接受需要下载文件名称
        String filename = req.getParameter("filename");

        File  file=new File(realPath+"/"+filename);

        InputStream  input=new FileInputStream(file);

        //[2]把读取到文件写到本地
        //必须写入到客户端位置才可以
        OutputStream  output=resp.getOutputStream();

         //设置下载文件的大小
        resp.setContentLength((int) file.length());
        //设置下载内容类型
        resp.setContentType(req.getParameter("filetype"));
        //设置响应头内容
        resp.setHeader("Content-Disposition","attachment;filename="+filename);


        IOUtils.copy(input,output);

        output.close();
        input.close();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/284176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号