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;
    }
相关推荐
白宇横流学长2 分钟前
基于SpringBoot实现的零食销售商城设计与实现【源码+文档】
java·spring boot·后端
qq_336313932 分钟前
Java基础-Stream流
java·开发语言·windows
驱动探索者8 分钟前
[缩略语大全]之[INTEL]篇
java·后端·spring·intel
老鼠只爱大米11 分钟前
Java设计模式之代理模式(Proxy)深度解析
java·设计模式·代理模式·proxy pattern·java设计模式·proxypattern
wepe1214 分钟前
FlyEnv---phpstudy平替
java·python·mysql·nginx·php
Echo flower17 分钟前
使用Java将HTML内容转换为Word文档
java·html·word
一人の梅雨17 分钟前
京东商品详情接口深度解析:从宙斯签名到商详数据价值重构
java·spring cloud·微服务
spencer_tseng20 分钟前
org.eclipse.wst.common.project.facet.core.xml could not be read.
xml·java·eclipse
Lisonseekpan20 分钟前
为什么Spring 推荐使用构造器注入而非@Autowired字段注入?
java·后端·spring·log4j