zoukankan      html  css  js  c++  java
  • spring配置环境下的文件上传以及上传的图片展示

    实现的效果目的:

      把本地的图片进行上传,并且保存至当前项目的tomcat服务器和数据库中,

    当需要展示图片的时候,我们拿数据库中绝对路径的相对路径,这个时候就需

    要在控制层进行绝对路径的处理,处理完后,就可以通过相对路径去匹配服务

    器中的图片相对路径,然后进行展示

     

    注意事项:

    a.存入数据库中的是决定路径,而不是相对路径,方便查找图片在电脑中存放的服务器下的位置

    b.前端页面的file的input框的name不能和数据库存放图片路径的字段一样

     

     c.新增用户信息的时候,注意生日的日期格式,必须在实体类中birthday属性加上注解

    文件上传以及展示的实现步骤:

    1.导入依赖:三个jar包  

      
    <dependencies>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
    </dependency>

    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
    </dependency>

    <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
    </dependency>

    <dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.6</version>
    </dependency>

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.1</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.1</version>
    </dependency>
    <dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
    </dependency>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.13</version>
    </dependency>

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.1</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.1</version>
    </dependency>

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    <scope>provided</scope>
    </dependency>

    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>

    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>

    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version>
    </dependency>
    <!--文件上传-->
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
    </dependency>
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
    </dependency>
    <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
    </dependency>
    </dependencies>

    2.springmvc的springmvc-serlvet配置文件中配置上传文件的配置信息

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="cn.smbms.controller"/>

    <mvc:annotation-driven/>

    <mvc:resources mapping="/statics/**" location="/statics/"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置文件上传的配置信息-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="maxUploadSize" value="5000000"/>
    </bean>

    </beans>

    3.useradd3.jsp页面需要一个file类型的input框

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
    <jsp:include page="/WEB-INF/jsp/common/head.jsp"/>

    <div>
    <h2>${uploadFileError}</h2>
    ${uploadFileError}
    <form action="/jsp/user/addSave3" method="post" enctype="multipart/form-data">
    <div class="form-row">
    <div class="form-group col-md-6">
    <label for="userCode">userCode</label>
    <input type="text" class="form-control" id="userCode" name="userCode" value="" placeholder="用户编码">
    </div>
    <div class="form-group col-md-6">
    <label for="userName">userName</label>
    <input type="text" class="form-control" id="userName" name="userName" value="" placeholder="用户昵称">
    </div>
    </div>
    <div class="form-row">
    <div class="form-group col-md-6">
    <label for="userPassword">userPassword</label>
    <input type="password" class="form-control" id="userPassword" name="userPassword" value="" placeholder="userPassword">
    </div>
    <div class="form-group col-md-6">
    <label for="gender">性别</label>
    <input type="text" class="form-control" id="gender" name="gender" value="" placeholder="性别:1 男, 2:女">
    </div>
    </div>

    <div class="form-row">
    <div class="form-group col-md-6">
    <label for="birthday">生日</label>
    <input type="text" class="form-control" id="birthday" name="birthday" value="" placeholder="birthday">
    </div>
    <div class="form-group col-md-6">
    <label for="phone">电话</label>
    <input type="text" class="form-control" id="phone" name="phone" value="" placeholder="phone">
    </div>
    </div>

    <div class="form-row">
    <div class="form-group col-md-6">
    <label for="address">地址</label>
    <input type="text" class="form-control" id="address" name="address" value="" placeholder="address">
    </div>
    <div class="form-group col-md-6">
    <label for="userRole">用户角色</label>
    <input type="text" class="form-control" id="userRole" name="userRole" value="" placeholder="userRole">
    </div>
    </div>
    <div class="form-row">
    <div class="form-group">
    <label for="idPicPath_a">个人身份证件照上传</label>
    <input type="file" class="form-control-file" id="idPicPath_a" name="multipartFiles" value=""
    placeholder="选择文件">
    </div>
    <div class="form-group">
    <label for="workPicPath_a">工作证件照上传</label>
    <input type="file" class="form-control-file" id="workPicPath_a" name="multipartFiles" value=""
    placeholder="选择文件">
    </div>
    </div>
    <input type="submit" class="btn btn-primary" value="新增"/>
    </form>
    </div>


    <jsp:include page="/WEB-INF/jsp/common/foot.jsp"/>


     4.userview3.jsp查看详情页面,进行文件上传的图片展示

    <%--
      Created by IntelliJ IDEA.
      User: liujie
      Date: 2020/12/18
      Time: 16:25
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>用户详情展示</h1>
        <div id="d_view">
                用户编码:<input type="text" name="userCode" id="userCode" value="${user.userCode}"><br>
                用户名称:<input type="text" name="userName" id="userName" value="${user.userName}"><br>
                用户密码: <input type="password" name="userPassword" id="userPassword" value="${user.userPassword}">
                性别:<input type="text" name="gender" id="gender" value="${user.gender}"><br>
                生日:<input type="text" name="birthday" id="birthday" value="${user.birthday}">
                电话:<input type="text" name="phone" id="phone" value="${user.phone}"><br>
                用户角色:<input type="text" name="userRole" id="userRole" value="${user.userRole}"><br>
                个人证件照片:<img src="${pageContext.request.contextPath}/statics/uploadfiles/${idPicRelPath}"> <br>
                个人工作证件照:<img src="${pageContext.request.contextPath}/statics/uploadfiles/${workPicRelPath}"> <br>
    
            <a href="javaScript:void(0);" id="view_return">返回</a>
        </div>
    </body>
    </html>
    

    5.userController类中的addSave方法行为中实现多文件上传

     /**
         * 多文件上传
         * multipartFiles[]类型的参数是和页面的file类型的input框绑定的
         * 通过注解@RequestParam("multipartFiles")锁定进行获取文件上
         * 传的name="multipartFiles"的标签中的信息
         * @param model
         * @param request
         * @param user
         * @param multipartFiles
         * @return
         */
        @RequestMapping("addSave3")
        public String addSave3(Model model
        ,HttpServletRequest request
        ,User user
        ,@RequestParam("multipartFiles")MultipartFile[] multipartFiles){
            if(multipartFiles.length>0){
    
                for (int i=0;i<multipartFiles.length;i++){
                    String idPicPath=null;
                    String workPicPath=null;
                    if(!multipartFiles[i].isEmpty()){
                        //获取服务器路径
                        String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
                        //获取原文件名
                        String originalFilename = multipartFiles[i].getOriginalFilename();
                        //获取后缀名
                        String suffix = FilenameUtils.getExtension(originalFilename);
                        //设置图片上传的大小限制
                        Integer fileSize=1024*1000;
                        if(multipartFiles[i].getSize()>fileSize){
                            model.addAttribute("uploadError","* 文件上传大小不能大于1mb");
                            return "user/useradd3";
                        }else if("jpg".equals(suffix)||"png".equals(suffix)
                        ||"jpeg".equals(suffix)||"pneg".equals(suffix)){
                            String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"Personal.png";
                            File targetFile = new File(path,fileName);
                            if(!targetFile.exists()){
                                //递归创建一个文件
                                targetFile.mkdirs();
                            }
                            //进行文件上传
                            try {
                                multipartFiles[i].transferTo(targetFile);
                                if(i==0){
                                    idPicPath=path+File.separator+fileName;
                                    user.setIdPicPath(idPicPath);
                                }
                                if(i==1){
                                    workPicPath=path+File.separator+fileName;
                                    user.setWorkPicPath(workPicPath);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }else{
                            model.addAttribute("uploadError","* 上传的图片格式不正确");
                        }
                    }
                }
            }
            //调用userService的userAdd方法进行用户新增
            int count = userService.userAdd(user);
            if(count>0){
                return "redirect:/jsp/user/query2";
            }
            model.addAttribute("uploadError","* 新增失败");
            return "user/useradd3";
        }
    

    6.userController类中的selectById3方法行为中进行用户详情的展示,并且展示上传文件的图片

       /**
         * 用户的查看详情
         * @param model
         * @param id
         * @param request
         * @return
         */
        @RequestMapping("selectById3")
        public String selectById3(Model model
        ,Long id
        ,HttpServletRequest request){
            User user = userService.queryUserById(id);
            //处理数据库存储的绝对路径
            String idPicPath = user.getIdPicPath();
            String workPicPath = user.getWorkPicPath();
            String[] arridPicPath = idPicPath.split("\\");
            String[] arrworkPicPath = workPicPath.split("\\");
    
            String idPicRelPath=arridPicPath[arridPicPath.length-1];
            String workPicRelPath=arrworkPicPath[arrworkPicPath.length-1];
            model.addAttribute("idPicRelPath",idPicRelPath);
            model.addAttribute("workPicRelPath",workPicRelPath);
            model.addAttribute("user",user);
            return "user/userview3";
        }
    

      

    7.效果截图

    1)------>用户新增页面

    2)------>点击选择文件后

     3)------->点击新增去userList3.jsp页面,然后点击尾页的最后一条数据

    4)-------->点击查看详情,进行上传文件的图片展示成功

    8.最后

    文章有点长,如果你耐心地看到这,也相信你会有点收获,作者会持续进行更新,还望你的小小关注走一走

  • 相关阅读:
    (五)SpringBoot如何定义全局异常
    从 vim 一题看线头 DP 的扩展应用
    Hadoop Shell基本操作
    《需求工程》阅读笔记*part1
    Jmeter系列(16)- 详解 HTTP Request
    Jmeter系列(15)- 配置元件的入门介绍
    Jmeter系列(14)- 前置、后置处理器的入门介绍
    Jmeter系列(13)- 断言Assertions 的入门介绍
    Jmeter系列(12)- 定时器Timers 的入门介绍
    Jmeter系列(11)- 监听器Listeners 的入门介绍
  • 原文地址:https://www.cnblogs.com/xiaojieDeam/p/14160285.html
Copyright © 2011-2022 走看看