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;
    }
相关推荐
爱笑的眼睛1126 分钟前
超越剪枝与量化:下一代AI模型压缩工具的技术演进与实践
java·人工智能·python·ai
阿里云云原生32 分钟前
Android App 崩溃排查指南:阿里云 RUM 如何让你快速从告警到定位根因?
android·java
历程里程碑34 分钟前
C++ 9 stack_queue:数据结构的核心奥秘
java·开发语言·数据结构·c++·windows·笔记·算法
醇氧1 小时前
【Windows】从守护到终结:解析一个 Java 服务的优雅停止脚本
java·开发语言·windows
努力发光的程序员1 小时前
互联网大厂Java求职面试实录
java·jvm·线程池·多线程·hashmap·juc·arraylist
小鹿学程序1 小时前
FileZilla连接到虚拟机
java·服务器·开发语言
Haooog1 小时前
Docker面试题(不定时更新)
java·docker·面试
feathered-feathered1 小时前
Redis基础知识+RDB+AOF(面试)
java·数据库·redis·分布式·后端·中间件·面试
毕设源码-赖学姐1 小时前
【开题答辩全过程】以 高校排课系统的优化设计与实现为例,包含答辩的问题和答案
java·eclipse
q_19132846951 小时前
基于SpringBoot2+Vue2的行业知识答题考试系统
java·vue.js·spring boot·mysql·毕业设计·计算机毕业设计·演示文稿