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开发工具——IDEA(修改全局配置,提升工作效率)
java·编辑器·intellij-idea
强子感冒了1 小时前
Java网络编程学习笔记,从网络编程三要素到TCP/UDP协议
java·网络·学习
二哈喇子!1 小时前
SpringBoot项目右上角选择ProjectNameApplication的配置
java·spring boot
sin22011 小时前
MyBatis的执行流程
java·开发语言·mybatis
二哈喇子!1 小时前
基于Spring Boot框架的车库停车管理系统的设计与实现
java·spring boot·后端·计算机毕业设计
二哈喇子!1 小时前
基于Spring Boot框架的网络游戏虚拟交易平台的设计与实现
java·springboot·毕设项目
二哈喇子!2 小时前
JAVA环境变量配置步骤及测试(JDK的下载 & 安装 & 环境配置教程)
java·开发语言
二哈喇子!2 小时前
基于SpringBoot框架的水之森海底世界游玩系统
spring boot·旅游
二哈喇子!2 小时前
Java框架精品项目【用于个人学习】
java·spring boot·学习
二哈喇子!2 小时前
基于SpringBoot框架的网上购书系统的设计与实现
java·大数据·spring boot