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

1、mapper.xml文件

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

2、pojo里,类型为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;
    }

读取

    @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、页面:

        <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">

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页