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;
    }
相关推荐
zero.cyx3 分钟前
javaweb(AI)-----后端
java·开发语言
鹿角片ljp4 分钟前
Java深入理解MySQL数据库操作
java·mysql·adb
NE_STOP6 分钟前
SpringBoot集成shiro
java
RemainderTime7 分钟前
从零搭建Spring Boot3.x生产级单体脚手架项目(JDK17 + Nacos + JWT + Docker)
java·spring boot·架构
黯叶10 分钟前
基于 Docker+Docker-Compose 的 SpringBoot 项目标准化部署(外置 application-prod.yml 配置方案)
java·spring boot·redis·docker
say_fall10 分钟前
泛型编程基石:C++ 模板从入门到熟练
java·开发语言·c++·编辑器·visual studio
代码笔耕12 分钟前
写了几年 Java,我发现很多人其实一直在用“高级 C 语言”写代码
java·后端·架构
txinyu的博客16 分钟前
结合游戏场景解析UDP可靠性问题
java·开发语言·c++·网络协议·游戏·udp
一路向北North17 分钟前
springboot基础(85): validator验证器
java·spring boot·后端
1.14(java)28 分钟前
掌握数据库约束:确保数据精准可靠
java·数据库·mysql·数据库约束