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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值