Spring boot+Mybatis图片存储至数据库

1.首先是mapper.xml SQL语句的代码 数据库字段类型为BLOB

<insert id="insertOne" parameterType="java.util.Map">
    insert into imgtest (img)
    values (#{img, jdbcType=BLOB})
</insert>

2.实体类的映射类型为
byte[]

3.Controller层
前台传过来文件接收转二进制存储数据库


    @RequestMapping(value = "/addImg", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addImg(HttpServletRequest request,
                                     @RequestParam("file") MultipartFile file){
 
        Map<String, Object> result = new HashMap<>();
        Map<String ,Object> params = new HashMap<>();
       
        try {
            byte[] data;
            data = file.getBytes();
            params.put("img", data);
            //插入数据库
        }catch (Exception e){
            e.printStackTrace();
        }
        result.put("message", "上传成功");
        return result;
}

4.Controller层
读取二进制图片

 @RequestMapping(value = "/getImgById", method = RequestMethod.GET)
    public void getImgById(@RequestParam(value = "id")Long id,
                           HttpServletResponse response){
        try {
            ImgTest imgTest = imgService.getImgById(id);
            byte[] data = imgTest.getImg();
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputSream = response.getOutputStream();
            outputSream.write(data);
            outputSream.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
        }

5.最后页面显示图片

        <form action="/addImg" enctype="multipart/form-data" method="post">
            <input type="file" name="file">
            <input type="submit" value="上传">
        </form>
 
        <br>
        <img src = "/getImgById?id=1">

你可能感兴趣的:(后端,java,mysql)