Spring boot实现图片上传和下载

在pom.xml中添加依赖:

html 复制代码
<dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
</dependency>

在controller中实现上传和下载

上传图片:

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

java 复制代码
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";
    }

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

java 复制代码
    @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;
    }
相关推荐
呼啦啦啦啦啦啦啦啦5 小时前
常见的排序算法
java·算法·排序算法
anlogic6 小时前
Java基础 8.18
java·开发语言
练习时长一年7 小时前
AopAutoConfiguration源码阅读
java·spring boot·intellij-idea
源码宝8 小时前
【智慧工地源码】智慧工地云平台系统,涵盖安全、质量、环境、人员和设备五大管理模块,实现实时监控、智能预警和数据分析。
java·大数据·spring cloud·数据分析·源码·智慧工地·云平台
David爱编程8 小时前
面试必问!线程生命周期与状态转换详解
java·后端
LKAI.9 小时前
传统方式部署(RuoYi-Cloud)微服务
java·linux·前端·后端·微服务·node.js·ruoyi
HeyZoeHey9 小时前
Mybatis执行sql流程(一)
java·sql·mybatis
2301_793086879 小时前
SpringCloud 07 微服务网关
java·spring cloud·微服务
柳贯一(逆流河版)10 小时前
Spring 三级缓存:破解循环依赖的底层密码
java·spring·缓存·bean的循环依赖
Q_Q196328847512 小时前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php