springMVC实现图片的上传与查看

 配置文件

dispatcher-servlet.xml

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件的最大大小,单位为字节 -->
        <property name="maxUploadSize" value="17367648787"></property>
        <!-- 上传文件的编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

前端输入界面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/vendor/bootstrap-4.3.1-dist/css/bootstrap.css}">
    <script th:inline="javascript">
        function previewImage(file){

            var img = document.getElementById('picImg');

            if (file.files && file.files[0])
            {

                //准备一个文件读取器对象,并告诉它文件读取完毕之后要做什么。
                var reader = new FileReader();
                //成功读取了图片信息后,把读取结果赋予

                //FileReader.readAsDataURL()
                //开始读取指定的Blob中的内容。一旦完成,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容。
                reader.onload = function(evt){
                    img.src= evt.target.result;
                    console.log("read ok! img src get value!"+evt.target.result);
                }

                console.log("start to read!")
                reader.readAsDataURL(file.files[0]);

            } else{
                img.src=[[@{/pics/no-pic.jpg}]];
                // alert("no upload file!");
            }
        }
    </script>
</head>
<body>
     <div class="container">
         <h2 class="my-5"><b>小区车辆管理系统</b> <small class="ml-3">业主登记注册</small> </h2>
         <div class="row">
             <div class="col-12 col-md-6">
                 <form th:action="@{/person}" method="post" enctype="multipart/form-data">
                     <div class="form-group">
                         <label>业主身份证</label>
                         <input name="idcard" class="form-control">
                     </div>
                     <div class="form-group">
                         <label>业主姓名</label>
                         <input name="name" class="form-control">
                     </div>
                     <div class="form-group">
                         <label>业主照片</label><br>
                         <img id="picImg" th:src="@{/pics/no-pic.jpg}" width="160" height="175" class="my-1"><br>
                         <input type="file" name="personPic" class="form-control-file" onchange="previewImage(this);">
                     </div>
                     <div class="form-group">
                         <label>身高</label>
                         <input name="height" class="form-control">
                     </div>
                     <div class="form-group">
                         <label>出生日期</label>
                         
                         <input name="birth" class="form-control">
                     </div>
                     <div class="form-group">
                         <label>住宅单元地址</label>
                         <input name="address" class="form-control">
                     </div>
                     <input type="submit" class="btn btn-primary" value="业主登记">
                 </form>
             </div>
         </div>
     </div>
</body>
</html>

提交到后端

    @PostMapping("/person")
    public String createPerson(Person person, @RequestParam("personPic") MultipartFile file) throws Exception{

//        log.info("create person now! person:"+person);
        person.setPhoto(file.getBytes());

        personService.registerPerson(person);

        log.info("create person ok! person:"+person);
        return "redirect:/person";
    }

到这里已经将图片转化成二进制数组到后端了,然后就是查看图片

     <form th:action="@{/person}" method="post">
         <input type="hidden" name="_method" value="DELETE">
     </form>
     <div class="container">
         <h2 class="my-5"><b>小区车辆管理系统</b> <small class="ml-3">业主信息表</small> </h2>
         <div class="row">
             <div class="col-12">
                 <table class="table">
                     <thead>
                     <tr>
                         <th scope="col">身份证</th>
                         <th scope="col">姓名</th>
                         <th scope="col">身高</th>
                         <th scope="col">出生日期</th>
                         <th scope="col">住址</th>
                         <th scope="col">操作</th>
                     </tr>
                     </thead>
                     <tbody>
                     <tr th:each="person:${personList}">
                         <th scope="row" th:text="${person.idcard}"></th>
                         <td>
                             <img th:src="@{'/person/'+${person.idcard}+'/pic'}" width="120" height="130" class="my-1"><br>
                             <span th:text="${person.name}"></span>
                         </td>
                         <td th:text="${person.height}"></td>
                         <td th:text="${#dates.format(person.birth, 'yyyy-MM-dd')}"></td>
                         <td th:text="${person.address}"></td>
                         <td>
                             <button class="btn btn-primary btn-sm" title="点击修改业主的信息" th:onclick="update_person([[${person.idcard}]])">修改</button>
                             <button class="btn btn-danger btn-sm"
                                     th:onclick="show_remove_dialog([[${person.name}]],[[${person.idcard}]])">删除</button>
                         </td>
                     </tr>
                     </tbody>
                 </table>
             </div>
         </div>
     </div>

获取图片时使用`th:src="@{'/person/'+${person.idcard}+'/pic'}"`将生成一个URL,其中身份证号码将被插入到URL中,以获取特定的图像。

URL对应的获取图片后端代码

    @GetMapping("/person/{idcard}/pic")     // /person/191801801099101/pic, 注入依赖
    public String getPersonPic(@PathVariable("idcard") String id,
                               HttpServletRequest request,
                               HttpServletResponse response ) throws  Exception{
//        System.out.println(id);
        log.debug("准备加载身份证号码为"+id+"的业主照片。");
        byte[] imgData  = personService.loadPicByPersonId(id);

        if(imgData==null || imgData.length==0){
            log.debug("没有找到身份证号码为"+id+"的业主照片,现在计划记载默认照片....");

            String defaultPicPath = request.getRealPath("/")+"pics/no-pic.jpg"; //真实磁盘路径和网页路径之间的差异。
            FileInputStream fis =new FileInputStream(defaultPicPath);
            imgData =new byte[fis.available()];
            fis.read(imgData);
            log.debug("默认照片加载完成!");
        }
        response.setContentType("image/jpeg");
        ServletOutputStream oos = response.getOutputStream();
        oos.write(imgData);
        oos.flush();
        oos.close();
        log.debug("身份证号码为"+id+"的业主照片输出到浏览器完毕");
        return null;
    }

mapper配置文件

    <select id="getPersonPic" parameterType="java.lang.String" resultMap="imgResultMap">
        select photo
        from tbl_person
        where idcard=#{idcard}
    </select>

要返回的值是一个byte[],一看这东西就不太好直接返回。

所以就创建一个resultMap,根据这个方法进行返回。以下是resultMap:

    <resultMap type="java.util.Map" id="imgResultMap" >
        <result  column="photo" property="imgBytes" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
    </resultMap>

图片真的麻烦,最终大功告成!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值