简介

在Web应用系统开发中,文件上传是必不可少的功能,本章我们将用spring提供的MultipartFile实现文件上传

看完本章你将会知道

如何实现异步上传文件,并实现简单地图片回显

配置文件

pom

 <?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>

    <groupId>com.boot</groupId>
    <artifactId>demo-file</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-file</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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-freemarker</artifactId>
        </dependency>
    </dependencies>

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


</project>

application.yml

sys:
  basePath: E:\picture\
  webPath: http://localhost:8080/
  imgPath: http://localhost:8080/image/
spring:
  mvc:
    static-path-pattern: /image/**
  resources:
    static-locations:  file:E://picture/

HelloFile

项目架构图

image.png

FileController

@Controller
public class FileController {

    @Value("${sys.basePath}")
    private String basePath;
    @Value("${sys.imgPath}")
    private String imgPath;

    /**
     * 实现文件上传
     */
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {//判断文件为null
            return ResultEnum.FILEISNULL.getMessage();
        }

        String fileName = file.getOriginalFilename();//获取文件名
        String path = basePath ;   //自定义文件存放位置
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
        String newName = UUID.randomUUID().toString()+suffix;
        File dest = new File(path + newName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();    //创建目录
        }
        try {
            file.transferTo(dest); //保存文件
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgPath+newName;
    }
}

PageController

@Controller
public class PageController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

ResultEnum

@Getter
public enum ResultEnum {
    FILEISNULL(1,"文件为null")
    ,UPLOADSUCCESS(2,"上传成功");

    private Integer code;
    private String message;

    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

DemoFileApplication

@SpringBootApplication
public class DemoFileApplication {

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

index.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="uploadForm">
    <input id="file" type="file" name="file"/>
    <button id="upload" type="button" onclick="fileUpload()">upload</button>
</div>

<h1>图片回显</h1>
<hr/>
<img src=""/>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script  >
    function fileUpload() {
        var formData = new FormData();
        formData.append('file', $('#file')[0].files[0]);
        $.ajax({
            url: '/fileUpload',
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false
        }).done(function (res) {
          $('img').attr('src',res);
        }).fail(function (res) {

        });
    }
</script>
</body>
</html>

run

git地址

gitee

Last Updated: 6/13/2019, 7:10:41 PM