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;
    }
相关推荐
爱笑的眼睛1121 分钟前
PyTorch Lightning:重新定义深度学习工程实践
java·人工智能·python·ai
Kevinyu_34 分钟前
责任链模式
java·hadoop·责任链模式
明洞日记37 分钟前
【设计模式手册012】责任链模式 - 请求处理的流水线艺术
java·设计模式·责任链模式
q***071442 分钟前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot
雨中飘荡的记忆1 小时前
Spring Alibaba AI 实战指南
java·ai编程
冰封剑心1 小时前
MiniCPM-V-2_6 (4-bit 量化)使用
java·前端·数据库
mqiqe1 小时前
【Spring AI MCP】四、MCP 服务端
java·人工智能·spring
l***74941 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
阿拉斯攀登1 小时前
安卓工控机 OTA 升级方案(SpringBoot+MQTT)
android·spring boot·物联网·iot
稚辉君.MCA_P8_Java1 小时前
Gemini永久会员 Java实现的暴力递归版本
java·数据结构·算法