Springboot 之 多文件上傳-知識林

本文章來自【知識林】

文件上傳在各種網站平臺上應用都非常廣泛,這篇文章將講述在Springboot中是如何完成文件上傳的,Springboot是打包運行的,上傳后的文件又該何去何從?

這篇文章需要用到前面所講的知識點《Springboot 之 靜態資源路徑配置》Thymeleaf相關的知識。

  • pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<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>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
</dependencies>

說明:頁面模板還是使用Thymeleaf,文件上傳工具使用Apache的commons-io

  • application.properties

此配置可參考《Springboot 之 靜態資源路徑配置》

server.port=1117
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

web.upload-path=D:/temp/upload/study17/

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:${web.upload-path}
  • Controller控制器
@Controller
public class IndexController {

    //獲取上傳的文件夾,具體路徑參考application.properties中的配置
    @Value("${web.upload-path}")
    private String uploadPath;

    /**
     * GET請求
     * 上傳頁面,也將顯示已經存在的文件
     * @param model
     * @return
     */
    @GetMapping(value = "/index")
    public String index(Model model) {
        //獲取已存在的文件
        File [] files = new File(uploadPath).listFiles();
        model.addAttribute("files", files);
        return "web/index";
    }

    /**
     * POST請求
     * @param request
     * @param files
     * @return
     */
    @PostMapping(value = "index")
    public String index(HttpServletRequest request, @RequestParam("headimg")MultipartFile[] files) {
        //可以從頁面傳參數過來
        System.out.println("name====="+request.getParameter("name"));
        //這里可以支持多文件上傳
        if(files!=null && files.length>=1) {
            BufferedOutputStream bw = null;
            try {
                String fileName = files[0].getOriginalFilename();
                //判斷是否有文件且是否為圖片文件
                if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                    //創建輸出文件對象
                    File outFile = new File(uploadPath + "/" + UUID.randomUUID().toString()+ getFileType(fileName));
                    //拷貝文件到輸出文件對象
                    FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bw!=null) {bw.close();}
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/index";
    }

    /**
     * 判斷文件是否為圖片文件
     * @param fileName
     * @return
     */
    private Boolean isImageFile(String fileName) {
        String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if(fileName==null) {return false;}
        fileName = fileName.toLowerCase();
        for(String type : img_type) {
            if(fileName.endsWith(type)) {return true;}
        }
        return false;
    }

    /**
     * 獲取文件后綴名
     * @param fileName
     * @return
     */
    private String getFileType(String fileName) {
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }
}

說明: @RequestParam("headimg")MultipartFile[] files這里的headimg是根據頁面上File inputname屬性而定。

  • index.html
<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>文件上傳</title>
    </head>
    <body>
        <h2>已有文件:</h2>
        <p th:each="file : ${files}">
            [站外圖片上傳中……(2)],文件名稱:<span th:text="${file.name}"></span>
        </p>
        <hr/>
        <form method="post" enctype="multipart/form-data">
            昵稱:<input name="name" type="text"/>
            <br/>
            頭像:<input name="headimg" type="file"/>
            <br/>
            <button type="submit">確定上傳</button>
        </form>
    </body>
</html>

注意:<input name="headimg" type="file"/>這里的headimg決定了Controller中@RequestParam("headimg")的值。如果有多個<input name="headimg" type="file"/>將是多文件上傳。

  • 頁面截圖

通過上面例子上傳兩張圖片后的效果:

多文件上傳-知識林

示例代碼:https://github.com/zsl131/spring-boot-test/tree/master/study17

本文章來自【知識林】

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,925評論 6 342
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 《Spring Boot開發:從0到1》 大綱結構v2.0 第一部分Spring Boot基礎 第1章 Sprin...
    光劍書架上的書閱讀 10,987評論 1 70
  • ——委內瑞拉考慮出售在美西果石油公司 近日,委內瑞拉政府老調重彈,再次公開表露了想要出售委內瑞拉國營石油公司旗下西...
    秦三十二閱讀 351評論 0 4
  • 晨風鳴鄉川,慵懶燕鶯都起,輾轉松梁柏棟前。柔柳梳翠,榆楊銜絮,忙不過阡陌田埂間,撒豆點點,一撮黃土貴如鹽。溪水濺山...
    懿語嫣然閱讀 299評論 2 1