springboot图片用二进制byte[]存放数据库,进行读取

本文介绍了一个使用Java实现的图片上传及通过ID获取图片的RESTful API示例。该API支持将图片作为二进制数据存储,并能通过HTTP GET请求返回指定ID的图片。文章详细展示了如何使用MultipartFile进行图片上传及如何通过图片ID获取图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 @RequestMapping(value="/{id}",method=RequestMethod.GET)
    public void getPhotoById (@PathVariable("id")Integer id, final HttpServletResponse response) throws Exception{  
        CustomerPicture find = customerPictureService.find(id);
        byte[] data = find.getPicture();  
        response.setContentType("image/jpeg");  
        response.setCharacterEncoding("UTF-8");  
        OutputStream outputSream = response.getOutputStream();
        outputSream.write(data);
        outputSream.flush();
        /*InputStream in = new ByteArrayInputStream(data);  
        int len = 0;  
        byte[] buf = new byte[1024];  
        while ((len = in.read(buf, 0, 1024)) != -1) {  
            outputSream.write(buf, 0, len);  
        }  
        outputSream.close(); *|
    }  
 @PostMapping("/insertCheckingRecord")
    public Result<CustomerPicture> insert(@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        Result<CustomerPicture> res = new Result<>();
        try {
        	CustomerPicture customerPicture = new CustomerPicture();
        	InputStream inputStream = file.getInputStream();
        	byte[] pictureData = new byte[(int) file.getSize()];
        	inputStream.read(pictureData);
        	customerPicture.setPicture(pictureData);
            CustomerPicture customerPicture1 = customerPictureService.insert(customerPicture);
            res.setStatus(StatusCode.SUCCESSFUL);
            res.setData(customerPicture1);
            res.setMessage(StatusCode.ADD_SUCCESSFUL_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            res.setStatus(StatusCode.FAILED);
            res.setMessage(StatusCode.ADD_FAILED_MSG + e.getMessage());
        }
        return res;
    }

转载:https://blog.youkuaiyun.com/jiawenlong_/article/details/41553375

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值