java实现文件上传的三种方式,java文件上传的几种方式

  java实现文件上传的三种方式,java文件上传的几种方式

  本文分享JavaWeb实现简单文件上传的具体代码,供大家参考。具体内容如下

  00-1010通常浏览器上传的所有参数都可以通过请求对象的GetParameter、GetParameter Map、GetParameter Value三种方法获得。但是有一种情况,当文件上传时带有包含的参数,这三种方法都是无效的,所以我们需要请求对象的getInputStream方法来获取这些参数。如何解析这个字节输入流?Apache Software Foundation 3360开发了一个工具,fileupload tool,分析字节输入流,实现文件上传功能。

  00-1010 2.1打开pom文件,加入fileupload的jar包依赖项。

  2.2三个要素

  1.该请求必须是post。2.表单属性必须包含enctype="multipart/form-data "。3.上传文本框输入type="file "必须具有name属性。

  2.3代码逻辑

  自定义一个parseRequest(request)方法,返回地图集,其中封装了商品添加功能中提交的所有数据;使用beans.populate (product,parameter map)的方法将map集合封装到product对象中;在业务层调用addProduct方法传递产品对象参数,在dao层将新添加的商品写入数据库;

  受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException { MapString,String[]parameter map=parse request(请求);//request . getparametermap();Product product=新产品();请尝试{ BeanUtils.populate(product,parameter map);} catch(Exception e){ e . printstacktrace();} productService.addProduct(产品);结果VO=新结果VO(结果VO。成功,空,商品添加成功);response.getWriter()。print(object mapper . writevalueasstring(resultVO));}实现parseRequest(request)方法, 实现文件上传功能:

  private MapString,String[]parse request(http servlet request请求){ MapString,String[] map=new HashMapString,String[]();//创建一个对象,磁盘工厂对象diskfileitemcfactory=newdiskfileitemcfactory();//创建一个负责解析请求流的对象,构造一个方法,传递磁盘工厂对象servlet file upload servlet file upload=new servlet file upload(diskfileitemcfactory);//获取当前日期。文件夹名称为simple date format SDF=new simple date format( yyyy-mm-DD );string string Date=SDF . format(new Date());Try {//解析对象的方法parseRequest解析一个Request对象//返回一个集合列表,集合的泛型,它是另一个对象3360 File Item对象//File Item对象3360客户端提交的任何数据都被认为是一个文件项(普通文本框,附件上传)//fileitem客户端的每个上传数据(当前情况是7个文件项)listfileitem fileitem List=servlet File upload . parse request(req

  uest);            //遍历集合,获取每个文件项对象  fileItem            for(FileItem fileItem : fileItemList){                //判断  fileItem文件项对象方法,判断出当前的文件项是普通文本,还是附件                if (fileItem.isFormField()){ //isFormField()返回true,普通项 , 返回false 是附件                    //普通文本,取出用户在文本框输入的数据,带编码表名                    String s = fileItem.getString("utf-8");                    //方法: 获取表单input的name的属性值                    String name = fileItem.getFieldName();                   //System.out.println(name+"==="+s);                    //数据,封装到Map集合                    map.put(name,new String[]{s});                }else {                    //方法isFormField()返回false,是附件项                    //FileItem对象方法 getName()获取到上传的文件名                    String fileName = fileItem.getName();                    //文件上传,是需要修改文件名                    //System.out.println(fileName); // Jellyfish.jpg                    //获取文件的后缀名,获取文件名 . 出现的索引                    int index =  fileName.lastIndexOf(".");                    //截取字符串                    fileName = fileName.substring(index);                    //System.out.println(fileName);                    //自定义新的文件名                    fileName = "itheima"+System.currentTimeMillis()+ UUIDUtil.getId()+fileName;                    //System.out.println(fileName);                    /**                     * 处理的上传路径,项目的目录 E:heima364storesrcmainwebappwebresourcesproducts                     * 开发的项目: 跨平台运行                     * Windows 系统路径  E:heima364storesrcmainwebappwebresourcesproducts                     * Linux 操作系统 /ss/ss/ss/ss                     * 路径定义在配置文件中,读取                     */                    ResourceBundle bundle = ResourceBundle.getBundle("uploadPath");                    //上传路径,读取配置文件                    String path = bundle.getString("path");                    //E:/heima364/store/src/main/webapp/web/resources/products /stringDate                    //File对象实现,路径的合并 (上传路径path,和日期字符串合并为一个路径)                    File uploadDir = new File(path,stringDate); //E:heima364storesrcmainwebappwebresourcesproducts2020-02-27                    //判断该路径是否存在                    if (!uploadDir.exists()){                        //不存在,就创建                        uploadDir.mkdirs();                    }                    //上传的路径 uploadDir 和文件名 fileName,组成一个新的File对象                    //E:heima364storesrcmainwebappwebresourcesproducts2020-02-27itheima158279119698617ad226bf52d4eb4bc9cd97dbbd1fd5a.jpg                    File uploadDirFile = new File(uploadDir,fileName);                    //文件赋值,字节流读取文件                    //文件项对象的方法, getInputStream获取输入流,读取的是上传的文件                    InputStream inputStream = fileItem.getInputStream();                    //字节的输出流                    FileOutputStream fileOutputStream = new FileOutputStream(uploadDirFile);                    //commonsIO工具的方法来实现                    IOUtils.copy(inputStream,fileOutputStream);                    fileOutputStream.close();                    //从上传的路径中uploadDirFile,获取出一部分路径,写入到数据库                    //File对象的方法toString(),路径转成字符串                    //获取resources出现的索引                    index = uploadDirFile.toString().indexOf("resources");                    String pimage = uploadDirFile.toString().substring(index);                    //替换路径中的 /                    pimage =pimage.replace("\","/");                    //路径,封装到Map集合中/                    map.put("pimage",new String[]{pimage});                    fileItem.delete();//删除上传的临时文件                }            }        }catch (Exception ex){            ex.printStackTrace();        }        //手动封装Map中缺少的数据        //商品主键        map.put("pid",new String[]{UUIDUtil.getId()});        //上架,固定为0        map.put("pflag",new String[]{"0"});        //商品的发布日期        map.put("pdate",new String[]{stringDate});        return map;    }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持盛行IT。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: