• Eclipse搭建springboot项目(三)配置文件自动注入+文件上传需求


    知识点1:SpringBoot2.x常见的配置文件 xml、yml、properties的区别和使用xml、properties、json、yaml

      1、常见的配置文件 xx.yml, xx.properties
        1) YAML(Yet Another Markup Language)
          写 YAML 要比写 XML 快得多(无需关注标签或引号)
          使用空格 Space 缩进表示分层,不同层次之间的缩进可以使用不同的空格数目
          注意:key后面的冒号,后面一定要跟一个空格,树状结构
          application.properties示例

    server.port=8090 
    server.session-timeout=30 
    server.tomcat.max-threads=0 
    server.tomcat.uri-encoding=UTF-8

          application.yml示例

    server: 
    port: 8090 
    session-timeout: 30 
    tomcat.max-threads: 0 
    tomcat.uri-encoding: UTF-8

      2、默认示例文件仅作为指导。 不要将整个内容复制并粘贴到您的应用程序中,只挑选您需要的属性。
      3、参考:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#common-application-properties

        如果需要修改,直接复制对应的配置文件,加到application.properties里面

    知识点2:SpringBoot注解把配置文件自动映射到属性和实体类实战

      简介:讲解使用@value注解配置文件自动映射到属性和实体类
      1、配置文件加载
      方式一
        1、Controller上面配置
          @PropertySource({"classpath:resource.properties"})
        2、增加属性
          @Value("${test.name}")
          private String name;

      方式二:实体类配置文件
        步骤

        1、添加 @Component 注解;
        2、使用 @PropertySource 注解指定配置文件位置;
        3、使用 @ConfigurationProperties 注解,设置相关属性;
        4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。

        @Autowired
        private ServerSettings serverSettings;

      例子:

    @Configuration
    @ConfigurationProperties(prefix="test")
    @PropertySource(value="classpath:resource.properties")
    public class ServerConstant {

        用(prefix="test")这种方式时变量不能加@Value("${test.name}")


      常见问题:
        1、配置文件注入失败,Could not resolve placeholder
        解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解, 默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,因此启动类最好放在根路径下面,或者指定扫描包范围spring-boot扫描启动类对应的目录和子目录。
        2、注入bean的方式,属性名称和配置文件里面的key一一对应,就不用加@Value 这个注解,如果不一样,就要加@value("${XXX}")

    知识点:SpringBoot2.x文件上传:HTML页面文件上传和后端处理

      1、springboot文件上传 MultipartFile file,源自SpringMVC
        1)静态页面直接访问:localhost:8080/index.html
          注意点:如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面
        2)MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
          访问路径 http://localhost:8080/images/39020dbb-9253-41b9-8ff9-403309ff3f19.jpeg

      2、jar包方式运行web项目的文件上传和访问处理,SpingBoot2.x使用 java -jar运行方式的图片上传和访问处理(核心知识)

        1)文件大小配置,启动类里面配置

    @Bean 
    public MultipartConfigElement multipartConfigElement() { 
        MultipartConfigFactory factory = new MultipartConfigFactory(); 
        //单个文件最大 
        factory.setMaxFileSize("10240KB"); //KB,MB 
        /// 设置总上传数据总大小 
        factory.setMaxRequestSize("1024000KB"); 
        return factory.createMultipartConfig(); 
    }

        2)打包成jar包,需要增加maven依赖,如果没加相关依赖,执行maven打包,运行后会报错:no main manifest attribute, in XXX.jar

           GUI:反编译工具,作用就是用于把class文件转换成java文件

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>     

        3)文件上传和访问需要指定磁盘路径
          application.properties中增加下面配置
            a) web.images-path=/Users/aaron/Desktop
            b) spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path}

        4)文件服务器:fastdfs,阿里云oss,nginx搭建一个简单的文件服务器

    一、目录结构

    二、文件上传需求

    1.前端

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>uploading</title>
    <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <script src="/js/test.js" type="text/javascript"></script>
    </head>
    <body>
        <form enctype="multipart/form-data" method="post" action="/fileController/upload">
            文件:<input type="file" name="head_img" /> 
            姓名:<input type="text" name="name" /> 
            <input type="submit" value="上传" />
        </form>
    </body>
    </html>

    2.文件上传Controller

    package net.aaron.demo.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import net.aaron.demo.domain.JsonData;
    
    @Controller
    @RequestMapping(value = "fileController")
    @PropertySource(value="classpath:application.properties")
    public class FileController {
        @Value("${web.filePath}")
        private String filePath;
        @RequestMapping(value = "upload")
        @ResponseBody
        public JsonData upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {
              
             //file.isEmpty(); 判断图片是否为空
             //file.getSize(); 图片大小进行判断
            
             System.out.println("配置注入打印,文件路径为:"+filePath);
             
             
             String name = request.getParameter("name");
             System.out.println("用户名:"+name);
            
             // 获取文件名
            String fileName = file.getOriginalFilename();            
            System.out.println("上传的文件名为:" + fileName);
            
            // 获取文件的后缀名,比如图片的jpeg,png
            // lastIndexOf 是从右向左查某个指定的字符串在字符串中最后一次出现的位置
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为:" + suffixName);
            
            // 文件上传后的路径
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("转换后的名称:"+fileName);
            
            File dest = new File(filePath + fileName);
           
         
    
                try {
                    file.transferTo(dest);
                     return new JsonData(0, fileName);
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  
            return  new JsonData(-1, "fail to save ", null);
        }
        
    }

    3.返回JsonData类

    package net.aaron.demo.domain;
    
    import java.io.Serializable;
    
    public class JsonData implements Serializable {
        
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        //状态码,0表示成功,-1表示失败
        private int code;
        
        //结果
        private Object data;
    
        //错误描述
        private String msg;
        
        
        public JsonData(int code, Object data) {
            super();
            this.code = code;
            this.data = data;
        }
        
        public JsonData(int code, String msg,Object data) {
            super();
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
    
    }

    4.访问:

    5.访问文件超过限制

    报错:org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field head_img exceeds its maximum permitted size of 1048576 bytes.

    解决:在启动类里面配置文件大小,验证OK

    package net.aaron.demo;
    
    import javax.servlet.MultipartConfigElement;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.MultipartConfigFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.util.unit.DataSize;
    import org.springframework.util.unit.DataUnit;
    
    @SpringBootApplication
    public class AaronSpringbootApplication {
    
    
    
        public static void main(String[] args) {
            SpringApplication.run(AaronSpringbootApplication.class, args);
        }
        
        @Bean 
        public MultipartConfigElement multipartConfigElement() { 
            MultipartConfigFactory factory = new MultipartConfigFactory(); 
            //单个文件最大 
            factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES)); //KB,MB 
            /// 设置总上传数据总大小 
            factory.setMaxRequestSize(DataSize.of(1000, DataUnit.MEGABYTES)); 
            return factory.createMultipartConfig(); 
        }
    
    }

    注:两种方式:

      1)配置项方式:

      application.properties

        spring.servlet.multipart.max-file-size=20MB
        spring.servlet.multipart.max-request-size=20MB

      2)直接传参方式

      springboot 1.5.X系列:

    /**  
         * 文件上传配置  
         * @return  
         */  
        @Bean  
        public MultipartConfigElement multipartConfigElement() {  
            MultipartConfigFactory factory = new MultipartConfigFactory();  
            //文件最大  
            factory.setMaxFileSize("10240KB"); //KB,MB  
            /// 设置总上传数据总大小  
            factory.setMaxRequestSize("102400KB");  
            return factory.createMultipartConfig();  
        }  

      Springboot 2.X系列:

     @Bean
        public MultipartConfigElement multipartConfigElement() {
            MultipartConfigFactory factory = new MultipartConfigFactory();
            //文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
            factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES));
            /// 设置总上传数据总大小10M
            factory.setMaxRequestSize(DataSize.of(10, DataUnit.MEGABYTES));
            return factory.createMultipartConfig();
        }
  • 相关阅读:
    单例模式
    抽象类的作用和应用场景
    java内部类的作用
    java多线程
    IO流--与properties集合配合使用
    IO流--序列化流与反序列化流
    8 个必备的PHP功能开发
    CSS3 box-shadow:
    移动平台的meta标签-----神奇的功效
    Android Screen Monitor抓取真机屏幕
  • 原文地址:https://www.cnblogs.com/aaronRhythm/p/10957409.html
Copyright © 2020-2023  润新知