springboot+mybatis上传图片保存到数据库,以及读取并在页面显示

1、mapper.xml文件


    insert into imgtest (img)
    values (#{img, jdbcType=BLOB})

2、pojo里,类型为byte[]

3、controller

存数据库

    @RequestMapping(value = "/addImg", method = RequestMethod.POST)
    @ResponseBody
    public Map addImg(HttpServletRequest request,
                                     @RequestParam("file") MultipartFile file){

        Map result = new HashMap<>();
        Map params = new HashMap<>();
       
        try {
            byte[] data;
            data = file.getBytes();
            params.put("img", data);
            //插入数据库
        }catch (Exception e){
            e.printStackTrace();
        }
        result.put("message", "上传成功");
        return result;
    }

读取

    @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();
        }
    }

4、页面:

        

 

你可能感兴趣的:(SpringBoot)