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;
    }
相关推荐
码农水水1 小时前
国家电网Java面试被问:TCP的BBR拥塞控制算法原理
java·开发语言·网络·分布式·面试·wpf
qq_336313932 小时前
java基础-网络编程-TCP
java·网络·tcp/ip
咕噜咕噜啦啦2 小时前
Java期末习题速通
java·开发语言
盐真卿2 小时前
python2
java·前端·javascript
一嘴一个橘子3 小时前
mybatis - 动态语句、批量注册mapper、分页插件
java
组合缺一3 小时前
Json Dom 怎么玩转?
java·json·dom·snack4
危险、4 小时前
一套提升 Spring Boot 项目的高并发、高可用能力的 Cursor 专用提示词
java·spring boot·提示词
kaico20184 小时前
JDK11新特性
java
钊兵4 小时前
java实现GeoJSON地理信息对经纬度点的匹配
java·开发语言
jiayong234 小时前
Tomcat性能优化面试题
java·性能优化·tomcat