SpringBoot------文件上传

1.pom.xml引入依赖配置

<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>
  <groupId>top.ytheng</groupId>
  <artifactId>springboot-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
              <scope>true</scope>
        </dependency>
    </dependencies>

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

2.添加文件控制器FileController

package top.ytheng.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 top.ytheng.demo.entity.JsonData;

@Controller
@PropertySource({"classpath:application.properties"})
public class FileController {
    @Value("${web.file.path}")
    private String filePath;
    
    @RequestMapping(value="/api/v1/file")
    public Object index() {
        return "index";
    }
    
    @RequestMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {
        //判断文件为空
        //file.isEmpty();
        //判断文件大小
        //file.getSize();
        
        String name = request.getParameter("name");
        System.out.println("用户名:" + name);
        //获取文件名称
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名称:" + fileName);
        
        //获取文件的后缀名
        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, null, fileName);
        } catch(IllegalStateException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        
        return new JsonData(-1, "上传失败");
    }
}

3.添加application.properties配置文件

#自定义文件上传路径
web.file.path=C:\Users\tianheng\eclipse-workspace\springboot-demo\src\main\resources\static\images\

#端口号
server.port=8090

4.添加upload.html界面

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<script type="text/javascript" src="/js/test.js" ></script>

<title>Insert title here</title>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/upload">
        文件:<input type="file" name="head_img"/>
        姓名:<input type="text" name="name"/>
        <input type="submit" value="上传"/>
    </form>
</body>
</html>

5.添加启动类

package top.ytheng.demo;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;

@SpringBootApplication //等于下面3个
//@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    //文件大小配置
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize("10240KB");
        //设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }
}

6.测试地址

http://localhost:8090/upload.html
原文地址:https://www.cnblogs.com/tianhengblogs/p/9757265.html