JavaWeb文件上传功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaWeb文件上传功能

辉者光也   2022-06-28 我要评论

1.概述

通常浏览器上传的所有参数,我们可以通过request对象的getParameter , getParameterMap , getParameterValue 这三个方法拿到所有的请求参数,
但有一种情况,当强求包含参数包含文件上传时, 这三个方法都失效,无法拿到参数,
我们就需要request对象的getInputStream方法获取这些参数, 如何解析这个字节输入流呢?
apache 软件基金会: 开发了工具fileupload工具, 专门解析字节输入流,实现文件上传功能.

2. 先导入jar包

2.1打开pom文件, 加入fileupload的jar包依赖.

2.2 三要素

1.必须post请求
2.form表单属性必须包含 enctype=“multipart/form-data”
3.上传文本框input type=“file” , 必须有name属性

2.3 代码逻辑

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

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> parameterMap = parseRequest(request);  //request.getParameterMap();
        Product product  = new Product();
        try {
            BeanUtils.populate(product,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        productService.addProduct(product);
        ResultVO resultVO = new ResultVO(ResultVO.SUCCESS,null,"商品添加成功");
        response.getWriter().print(objectMapper.writeValueAsString(resultVO));
    }

实现parseRequest(request)方法, 实现文件上传功能:

private Map<String,String[]> parseRequest(HttpServletRequest request) {
        Map<String,String[]> map = new HashMap<String, String[]>();
        //创建对象,磁盘工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //创建负责解析Request流的对象,构造方法,传递磁盘工厂对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        //获取当前日期,文件夹名字使用
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String stringDate = sdf.format(new Date());

        try {
            //解析对象的方法,parseRequest,解析reqeust对象
            //返回集合 List, 集合的泛型,是另一个对象: 文件项对象
            //文件项对象: 客户端提交的任何数据,都认为是一个文件项 (普通文本框,附件上传)
            //FileItem 客户端的每一个上传数据 (当前案例是7 个 文件项)
            List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
            //遍历集合,获取每个文件项对象  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:\heima364\store\src\main\webapp\web\resources\products
                     * 开发的项目: 跨平台运行
                     * Windows 系统路径  E:\heima364\store\src\main\webapp\web\resources\products
                     * 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:\heima364\store\src\main\webapp\web\resources\products\2020-02-27
                    //判断该路径是否存在
                    if (!uploadDir.exists()){
                        //不存在,就创建
                        uploadDir.mkdirs();
                    }
                    //上传的路径 uploadDir 和文件名 fileName,组成一个新的File对象

                    //E:\heima364\store\src\main\webapp\web\resources\products\2020-02-27\itheima158279119698617ad226bf52d4eb4bc9cd97dbbd1fd5a.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;
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们