欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot实现文件上传

程序员文章站 2022-06-02 14:09:47
...

Spring Boot实现文件上传功能

环境:maven3.3.3
     jdk1.8
     Spring Boot 1.5.15.RELEASE

1. pom文件中引入相关的依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.15.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. 在classpath的static目录下新建一个html文件upload.html,编写前段代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="fileupload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" name="提交">
    </form>
</body>
</html>

3. 编写controller

/**
 * 文件上传,文件上传后保存在D盘根目录下,文件保存后的名字为原文件名称
 *
 */
@RestController
public class FileUploadController {

    @RequestMapping("/fileupload")
    public Map<String, Object> uploadFile(MultipartFile file) throws Exception{
        file.transferTo(new File("d:/"+file.getOriginalFilename()));
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "ok");
        return map;
    }
}

4. 编写启动类,启动测试

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

5. 设置文件上传的默认值

需要在classpath下添加SpringBoot的配置文件:application.properties
在配置文件中加入以下配置:
设置单个上传文件的大小:spring.http.multipart.maxFileSize=200MB
设置一次请求上传文件的总容量:spring.http.multipart.maxRequestSize=200MB

6. 测试结果

Spring Boot实现文件上传
Spring Boot实现文件上传