zoukankan      html  css  js  c++  java
  • springboot测试简单上传文件

    springboot测试简单上传文件

    先看看目录结构
    1
    一、引入相应的pom文件

    <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-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    

    二、编写对应的配置文件

    spring.thymeleaf.encoding=utf-8
    spring.thymeleaf.prefix=classpath:/templates/
    
    #上传文件的大小
    spring.servlet.multipart.max-request-size=10MB
    #上传单个文件的大小
    spring.servlet.multipart.file-size-threshold=10MB
    

    三、编写一个控制器进行测试

    @Controller
    public class IndexController {
        private static final Logger logger= LoggerFactory.getLogger(IndexController.class);
    
        @GetMapping("/upload")
        public String upload(){
            return "upload";
        }
    
        @PostMapping("/upload")
        @ResponseBody
        public String upload(@RequestParam("file") MultipartFile file){
            if(file.isEmpty()){
                return "上传失败";
            }
            String fileName=file.getOriginalFilename();
            String filepath="F:/Test/";
            File dest = new File(filepath + fileName);
    
            try {
                file.transferTo(dest);
                logger.info("上传成功");
                return "上传成功";
            } catch (IOException e) {
                logger.error("上传失败");
                e.printStackTrace();
            }
            return "上传失败";
        }
    }
    
    

    结果:
    2
    上传成功
    3
    上传成功的文件
    4
    这里推荐一个我的个人博客,谢谢!

    天涯志

  • 相关阅读:
    leetcode 13. Roman to Integer
    python 判断是否为有效域名
    leetcode 169. Majority Element
    leetcode 733. Flood Fill
    最大信息系数——检测变量之间非线性相关性
    leetcode 453. Minimum Moves to Equal Array Elements
    leetcode 492. Construct the Rectangle
    leetcode 598. Range Addition II
    leetcode 349. Intersection of Two Arrays
    leetcode 171. Excel Sheet Column Number
  • 原文地址:https://www.cnblogs.com/cainiaoxiaoxie/p/12748384.html
Copyright © 2011-2022 走看看