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;
    }
相关推荐
文丑颜不良啊33 分钟前
LeetCode3001~3020题目解析
java·leetcode
山楂树の2 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
Java内核笔记2 小时前
方法级 trace 看不出第几轮:给 Agent 补一层轮次维度
人工智能·spring boot·后端
她的男孩3 小时前
转办给同事后对方一点同意就报幂等冲突:Forge Admin 不把转办键当成终态
spring boot·低代码·工作流引擎
.痞老板.3 小时前
java ee--文件操作和IO
java·java-ee
简 洁 冬冬3 小时前
分页「向上取整」公式 `(total + size - 1) / size` 的完整推导
java·分页
装不满的克莱因瓶5 小时前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
SimonKing6 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
Resean02236 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海6 小时前
现代c++4.1
java·开发语言·c++