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;
    }
相关推荐
java小白小10 分钟前
SpringBoot(01): 初识SpringBoot,从Spring的痛点说起
spring boot
用户128526116023 小时前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
java
Linsk3 小时前
组件 = 模板 + 业务逻辑
java·前端·vue.js
星沉远浦4 小时前
用Gemini高效解决Java代码报错难以定位的问题
java
用户3169353811837 小时前
如何从零编写一个 Spring Boot Starter
spring boot
用户298698530148 小时前
Word 文档字符级格式化:Java 实现方案详解
java·后端
笨鸟飞不快8 小时前
从单个服务到集群:一次完整的性能排查复盘
java·前端
荣码8 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
SamDeepThinking8 小时前
Java微服务练习方式
java·后端·微服务
朦胧之19 小时前
AI 编程-老项目改造篇
java·前端·后端