Spring boot实现图片上传和下载

在pom.xml中添加依赖:

<dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
</dependency>

在controller中实现上传和下载

上传图片:

图片的base64格式为字符串,以“data:image/png;base64,”开头,解码前需要去掉开头。

import org.apache.commons.codec.binary.Base64;
   

 @PostMapping(value = "/uploadImage",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public String uploadImage(@RequestBody Map<String,Object> map) throws IOException {
    	try {
    		Map<String,Object> m = (Map<String,Object>)map.get("img");
    		String imgStr = m.get("base64").toString();
    		imgStr = imgStr.substring(imgStr.indexOf(",", 1) + 1);

            byte[] bytes = Base64.decodeBase64(imgStr);

            String name = System.currentTimeMillis()+".png";       
            File file = new File("pictures/"+name);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            return "False";
        }

        return "True";
    }

下载图片:将图片转成字节数组。

    @RequestMapping(value = "/getImage",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(String path) throws IOException {
        File file = new File("pictures/"+path);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        inputStream.close();
        return bytes;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值