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;
    }
相关推荐
用户2986985301417 分钟前
Java 实现 Word 文档内容复制:段落、章节与全文合并技巧
java·后端
摇滚侠21 分钟前
Maven 入门+高深 SSM 案例 111-112
java·数据库·maven
Chase_______25 分钟前
【Java基础 | 16】集合框架(下):Map、HashMap 与 TreeMap
java·windows
Aaswk33 分钟前
Java项目:文件批量处理工具
java·开发语言·vscode·idea
小江的记录本37 分钟前
【Spring全家桶】Spring AI核心原理、大模型集成、Prompt工程、RAG实现、AI Agent开发(附《思维导图》+《面试高频考点清单》)
java·人工智能·spring boot·后端·spring·面试·prompt
plainGeekDev41 分钟前
线程安全集合 → 协程安全替代
android·java·kotlin
手握风云-1 小时前
Spring AI:让大模型住进 Spring 生态(五)
java·后端·spring
plainGeekDev1 小时前
Timer → Coroutines
android·java·kotlin
云烟成雨TD1 小时前
Spring AI 1.x 系列【40】MCP 客户端 Spring Boot 启动器
人工智能·spring boot·spring
糖果店的幽灵1 小时前
Spring AI 从入门到精通-Spring AI 是什么
java·人工智能·spring