基于SpringBoot的文件上传

在实际的企业开发中,文件上传是最常见的功能之一,SpringBoot集成了SpringMVC常用的功能,当然也包含了文件上传的功能,实现起来没有太多的区别。

下面我们来讲解一下,使用SpringBoot如何实现多个文件上传操作。使用的环境是IntelliJ IDE开发工具。

第一章:使用SpringBoot上传单个文件

开发过程如下:

第一步:配置pom.xml文件

<?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.sudojava.springboot_upload</groupId>
   <artifactId>springboot_upload</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>springboot_upload</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.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-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>
      </dependency>
   </dependencies>

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


</project>

第二步:单个文件上传的Controller类

package com.sudojava.springboot_upload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
public class SimpleFileController {


    @RequestMapping(value = "/uploadsimplefile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadSimpleFile(@RequestParam("attachment") MultipartFile file, HttpServletRequest request) {
        try {
            String fileDir = request.getSession().getServletContext().getRealPath("/upload/");
            System.out.println("------->>"+fileDir);
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            File upload_file = new File(fileDir + fileName);
            file.transferTo(upload_file);

        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
}

第三步:文件上传的页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>文件上传</title>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
    <!--引入CSS样式-->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">单个文件上传</h3>
        </div>
        <div class="panel-body">
            <form class="form-horizontal" method="post" enctype="multipart/form-data" th:action="@{/uploadsimplefile}" role="form">
                <div class="form-group">
                    <label for="attachment" class="col-sm-2 control-label">文件上传:</label>
                    <div class="col-sm-5">
                        <input type="file" class="form-control" name="attachment" id="attachment" placeholder="请选择邮件附件"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default">上 传</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<!--导入j是文件-->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

第二章:使用SpringBoot上传多个文件

package com.sudojava.springboot_upload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UploadFileController {


    @RequestMapping(value = "/uploadsimplefile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadSimpleFile(@RequestParam("attachment") MultipartFile file, HttpServletRequest request) {
        try {
            String fileDir = request.getSession().getServletContext().getRealPath("/upload/");
            System.out.println("------->>"+fileDir);
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            File upload_file = new File(fileDir + fileName);
            file.transferTo(upload_file);

        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }


    @RequestMapping(value = "/uploadmultifile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadMultiFile(@RequestParam("attachment") MultipartFile[] file, HttpServletRequest request) {
        try {
            String fileDir = request.getSession().getServletContext().getRealPath("/upload/");
            System.out.println("------->>"+fileDir);
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            for (int i=0;i<file.length;i++){
                if (file[i]!=null){
                    uploadFile(fileDir,file[i]);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
    /**
     *
     * @param uploadDir
     * @param file
     * @throws IOException
     */
    public void uploadFile(String uploadDir,MultipartFile file) throws IOException{
        String file_name = file.getOriginalFilename();
        File upload_file = new File(uploadDir+file_name);
        file.transferTo(upload_file);
    }
}

上传的HTML界面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>文件上传</title>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
    <!--引入CSS样式-->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">单个文件上传</h3>
        </div>
        <div class="panel-body">
            <form class="form-horizontal" method="post" enctype="multipart/form-data" th:action="@{/uploadmultifile}" role="form">
                <div class="form-group">
                    <label for="attachment1" class="col-sm-2 control-label">文件上传:</label>
                    <div class="col-sm-5">
                        <input type="file" class="form-control" name="attachment" id="attachment1" placeholder="请选择邮件附件"/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="attachment2" class="col-sm-2 control-label">文件上传:</label>
                    <div class="col-sm-5">
                        <input type="file" class="form-control" name="attachment" id="attachment2" placeholder="请选择邮件附件"/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="attachment3" class="col-sm-2 control-label">文件上传:</label>
                    <div class="col-sm-5">
                        <input type="file" class="form-control" name="attachment" id="attachment3" placeholder="请选择邮件附件"/>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-default">上 传</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<!--导入j是文件-->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>