java基于spring boot本地上传图片示例解析

前几天项目中刚好需要上传图片的需求,当时想的是用七牛云,因为我用七牛云也用了好几次,就是把图片上传到七牛云空间里面,数据库里面保存的是这张上传图片的url地址 那么页面访问也就很方便,考虑到项目部署的环境我就用了本地上传,不牵涉数据库的操作。我就花了半个小时写了个本地上传图片的小demo。非常的简单。

下面是需要的依赖 pom.xml文件:

 <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.1.3.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.com.sctic</groupId>
    <artifactId>upload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>upload</name>
    <description>Demo project for Spring Boot</description>
  
    <properties>
      <java.version>1.8</java.version>
    </properties>
  
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
  
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
  
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
      </dependency>
      
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
      </dependency>
      
    </dependencies>
    <build>
      <plugins>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
      </plugins>
    </build>
  </project>

控制器: UploadController

 @Controller
  public class UploadController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
  
    @Value("${scitc.upload.src}")
    private String rootPath;
  
    @Value("${scitc.upload.host}")
    private String uploadhost;
  
    @RequestMapping(value = "/uploadFile",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String uploadFile(MultipartFile file) {
  
      //文件的完整名称,如spring.jpeg
      String filename = file.getOriginalFilename();
      //文件名,如spring
      String name = filename.substring(0,filename.indexOf("."));
      //文件后缀,如.jpeg
      String suffix = filename.substring(filename.lastIndexOf("."));
  
      //创建年月文件夹
      Calendar date = Calendar.getInstance();
      File dateDirs = new File(date.get(Calendar.YEAR)
          + File.separator + (date.get(Calendar.MONTH)+1));
  
      //目标文件
      File descFile = new File(rootPath+File.separator+dateDirs+File.separator+filename);
      int i = 1;
      //若文件存在重命名
      String newFilename = filename;
      while(descFile.exists()) {
        newFilename = name+"("+i+")"+suffix;
        String parentPath = descFile.getParent();
        descFile = new File(parentPath+File.separator+newFilename);
        i++;
      }
      //判断目标文件所在的目录是否存在
      if(!descFile.getParentFile().exists()) {
        //如果目标文件所在的目录不存在,则创建父目录
        descFile.getParentFile().mkdirs();
      }
      //将内存中的数据写入磁盘
      try {
        file.transferTo(descFile);
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("上传失败,cause:{}",e);
      }
      //完整的url
      String fileUrl = uploadhost + rootPath +dateDirs+ "/"+newFilename;
      return "success:" + fileUrl;
    }
  }

注意:rootPath,uploadhost是可以通过application.properties或者application.yml进行配置的。

由于要对外部资源进行映射需要创建一个类继承WebMvcConfigurationSupport这个适配器,下面是WebMvcConfigurer的这个配置类,代码如下:

 @Configuration
  public class WebMvcConfigurer extends WebMvcConfigurationSupport {
    @Value("${scitc.upload.src}")
    private String src;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler(src + "/**").addResourceLocations("file:" + src);
    }
  }

注意:这里的src也是从配置文件applicaiton.properties中得到了。

下面是application.properties配置:

 server.port=8848 
	  ##文件上传config
	  scitc.upload.host:127.0.0.1:${server.port}
	  scitc.upload.src=/Users/jswzj/Desktop/uploads/
	  spring.servlet.multipart.maxFileSize=10MB
	  spring.servlet.multipart.maxRequestSize=10MB

	   server.port=8848 服务器的端口号
	   scitc.upload.host:服务器ip地址 + server.port
	   scitc.upload.src:你要把用户上传的图片上传到那个位置**

最后我们访问这个接口效果图如下:


上传成功后拿到这个url地址 粘贴到浏览器地址上就能访问了

总结:图片上传有很多的方式,当然这个是根据业务的需求,很多人都喜欢把图片的url上传到数据库中,用实体类来对图片的高度、宽度、名称、url进行封装,我觉得如果你部署的那台服务器是有网络的环境下建议用七牛云上传,七牛云上传把图片保存到七牛云空间,那个url地址是不会发生变化的,不会应为你项目的迁移或者服务器地址发生变化而受影响。看各自的需求吧。等有时间我会出一个七牛云上传的demo让大家学习。最后谢谢大家的支持,希望大家每天都要收获。祝大家早日成为大神。

下面是这个demo的github的地址,希望大家fork,start一下,谢谢

https://github.com/zhoubiao188/springboot-upload

到此这篇关于java基于spring boot本地上传图片示例解析的文章就介绍到这了,更多相关spring boot本地上传图片内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。