1. 程式人生 > >29. Spring boot 檔案上傳(多檔案上傳)【從零開始學Spring Boot】

29. Spring boot 檔案上傳(多檔案上傳)【從零開始學Spring Boot】

【視訊&交流平臺】

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

https://gitee.com/happyangellxq520/spring-boot

http://412887952-qq-com.iteye.com/blog/2321532



檔案上傳主要分以下幾個步驟

(1)新建maven java project;

(2)在pom.xml加入相應依賴;

(3)新建一個表單頁面(這裡使用thymeleaf);

(4)編寫controller;

(5)測試;

(6)對上傳的檔案做一些限制;

(7)多檔案上傳實現

(1)新建maven java project

新建一個名稱為spring-boot-fileuploadmaven java專案;

(2)在pom.xml加入相應依賴;

加入相應的maven依賴,具體看以下解釋:

<!--

              springboot父節點依賴,

引入這個之後相關的引入就不需要新增version配置,

              springboot會自動選擇最合適的版本進行新增。

        -->

       <parent>

              <groupId>org.springframework.boot</groupId>

              <artifactId>spring-boot-starter-parent</artifactId>

              <

version>1.3.3.RELEASE</version>

       </parent>

 <dependencies>

          <!-- spring boot web支援:mvc,aop... -->

              <dependency>

                     <groupId>org.springframework.boot</groupId>

                     <artifactId>spring-boot-starter-web</artifactId>

              </dependency>

              <!-- thmleaf模板依賴. -->

              <dependency>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-starter-thymeleaf</artifactId>

              </dependency>

 </dependencies>

     <build>

              <plugins>

                     <!-- 編譯版本; -->

                     <plugin>

                            <artifactId>maven-compiler-plugin</artifactId>

                            <configuration>

                                  <source>1.8</source>

                                  <target>1.8</target>

                            </configuration>

                     </plugin>

              </plugins>

       </build>

(3)新建一個表單頁面(這裡使用thymeleaf)

在src/main/resouces新建templates(如果看過博主之前的文章,應該知道,templates是spring boot存放模板檔案的路徑),在templates下新建一個file.html:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"

     xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>

       <title>Hello World!</title>

   </head>

   <body>

      <form method="POST" enctype="multipart/form-data"action="/upload"> 

              <p>檔案:<input type="file" name="file"/></p>

          <p><input type="submit" value="上傳" /></p>

      </form>

   </body>

</html>

(4)編寫controller;

編寫controller進行測試,這裡主要實現兩個方法:其一就是提供訪問的/file路徑;其二就是提供post上傳的/upload方法,具體看程式碼實現:

package com.kfit;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestParam;

importorg.springframework.web.bind.annotation.ResponseBody;

importorg.springframework.web.multipart.MultipartFile;

@Controller

publicclass FileUploadController {

       //訪問路徑為:http://127.0.0.1:8080/file

       @RequestMapping("/file")

       public String file(){

              return"/file";

       }

       /**

        *檔案上傳具體實現方法;

        *@param file

        *@return

        */

       @RequestMapping("/upload")

       @ResponseBody

       public StringhandleFileUpload(@RequestParam("file")MultipartFilefile){

              if(!file.isEmpty()){

                     try {

                            /*

                             *這段程式碼執行完畢之後,圖片上傳到了工程的跟路徑;

                             *大家自己擴散下思維,如果我們想把圖片上傳到 d:/files大家是否能實現呢?

                             *等等;

                             *這裡只是簡單一個例子,請自行參考,融入到實際中可能需要大家自己做一些思考,比如:

                             * 1、檔案路徑;

                             * 2、檔名;

                             * 3、檔案格式;

                             * 4、檔案大小的限制;

                             */

                            BufferedOutputStreamout =newBufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));

                            out.write(file.getBytes());

                            out.flush();

                            out.close();

                     }catch(FileNotFoundExceptione) {

                            e.printStackTrace();

                            return "上傳失敗,"+e.getMessage();

                     }catch (IOExceptione) {

                            e.printStackTrace();

                            return "上傳失敗,"+e.getMessage();

                     }

                     return "上傳成功";

              }else{

                     return "上傳失敗,因為檔案是空的.";

              }

       }

}

(5)編寫App.java然後測試

       App.java沒什麼程式碼,就是Spring Boot的啟動配置,具體如下:

package com.kfit;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

/**

 * Hello world!

 *

 */

//其中@SpringBootApplication申明讓spring boot自動給程式進行必要的配置,等價於以預設屬性使用@Configuration,@EnableAutoConfiguration和@ComponentScan

@SpringBootApplication

publicclass App {

       publicstaticvoid main(String[]args) {

              SpringApplication.run(App.class,args);

       }

}

進行測試了,檔案上傳的路徑是在工程的跟路徑下,請重新整理檢視,其它的請檢視程式碼中的註釋進行自行思考。

(6)對上傳的檔案做一些限制;

對檔案做一些限制是有必要的,在App.java進行編碼配置:

@Bean 

   public MultipartConfigElement multipartConfigElement() { 

        MultipartConfigFactoryfactory =newMultipartConfigFactory();

        //// 設定檔案大小限制 ,超了,頁面會丟擲異常資訊,這時候就需要進行異常資訊的處理了;

        factory.setMaxFileSize("128KB"); //KB,MB

        /// 設定總上傳資料總大小

        factory.setMaxRequestSize("256KB"); 

        //Sets the directory location wherefiles will be stored.

        //factory.setLocation("路徑地址");

        returnfactory.createMultipartConfig(); 

    } 

(7)多檔案上傳實現

多檔案對於前段頁面比較簡單,具體程式碼實現:

在src/resouces/templates/mutifile.html

<!DOCTYPEhtml>

<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>

        <title>Hello World!</title>

   </head>

   <body>

      <formmethod="POST"enctype="multipart/form-data"action="/batch/upload"> 

             <p>檔案1:<inputtype="file"name="file"/></p>

             <p>檔案2:<inputtype="file"name="file"/></p>

             <p>檔案3:<inputtype="file"name="file"/></p>

           <p><inputtype="submit"value="上傳"/></p>

      </form>

   </body>

</html>

com.kfit.FileUploadController中新增兩個方法:

/**

        *多檔案具體上傳時間,主要是使用了MultipartHttpServletRequest和MultipartFile

        *@param request

        *@return

        */

       @RequestMapping(value="/batch/upload", method=RequestMethod.POST

   public@ResponseBody 

   String handleFileUpload(HttpServletRequestrequest){ 

        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file"); 

        MultipartFile file = null;

        BufferedOutputStream stream = null;

        for (inti =0;i< files.size(); ++i) { 

            file = files.get(i); 

            if (!file.isEmpty()) { 

                try

                    byte[]bytes =file.getBytes(); 

                    stream

                            newBufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); 

                    stream.write(bytes); 

                    stream.close(); 

                } catch (Exceptione) { 

                       streamnull;

                    return"You failed to upload " +i + " =>" +e.getMessage(); 

                } 

            } else

                return"You failed to upload " +i + " becausethe file was empty."

            } 

        } 

        return"upload successful"

    } 

Spring Boot 系列視訊】

視訊&交流平臺:

http://study.163.com/course/introduction.htm?courseId=1004329008

http://412887952-qq-com.iteye.com/blog/2321532

網易雲課堂視訊最新更新

第十一章 Spring Boot 日誌

1、spring boot日誌—理論

2、Spring Boot日誌-logback

3、Spring Boot日誌-log4j2

第十二章 Spring Boot 知識點2

1、spring boot 服務配置和部署

2、Spring Boot 定製URL匹配規則

歷史章節

第一章 快速開始

1、Spring Boot之Hello World

2、Spring Boot之Hello World訪問404

第二章 Spring Boot之JSON

1、spring boot返回json資料

2、Spring Boot完美使用FastJson解析JSON資料

第三章 Spring Boot熱部署

1、Spring Boot熱部署(springloader)

2、springboot + devtools(熱部署)

第四章 Spring Boot資料庫

1、Spring Boot JPA/Hibernate/Spring Data概念

2、Spring Boot JPA-Hibernate

3、Spring Boot Spring Data JPA介紹

4、Spring Boot JdbcTemplate

5、Spring Boot整合MyBatis

第五章 web開發

1、全域性異常捕捉

2、配置server資訊

3、spring boot使用thymeleaf

4、Spring Boot 使用freemarker

5、Spring Boot新增JSP支援

第六章 定時任務

1、Spring Boot定時任務

2、Spring Boot 定時任務升級篇(動態修改cron引數)

3、Spring Boot 定時任務升級篇(動態新增修改刪除定時任務)

4、Spring Boot 定時任務升級篇(叢集/分散式下的定時任務說明)

5、Spring Boot Quartz介紹

6、Spring Boot Quartz在Java Project中使用

7、Spring Boot 整合Quartz普通使用

8、Spring Boot 整合Quartz升級版

9、Spring Boot 整合Quartz二次升級版

10、Spring Boot 整合Quartz-Job如何自動注入Spring容器託管的物件

第七章 Spring Boot MyBatis升級篇

1、Spring Boot MyBatis升級篇-註解

2、Spring Boot MyBatis升級篇-註解-自增ID

3、Spring Boot MyBatis升級篇-註解-增刪改查

4、Spring Boot MyBatis升級篇-註解-分頁查詢

5、Spring Boot MyBatis升級篇-註解-分頁PageHelper不生效

6、Spring Boot MyBatis升級篇-註解- mybatic insert異常:BindingException: Parameter 'name' not found

7、Spring Boot MyBatis升級篇-註解- #和$符號特別篇

8、Spring Boot MyBatis升級篇-註解[email protected]

9、Spring Boot MyBatis升級篇-註解-動態SQL(if test)-方案一:<script>

10、Spring Boot MyBatis升級篇-註解-動態SQL(if test)-方案二:@Provider

11、Spring Boot MyBatis升級篇-註解-動態SQL-引數問題

12、Spring Boot MyBatis升級篇-註解-特別篇:@MapperScan和@Mapper

13、Spring Boot MyBatis升級篇-XML

14、Spring Boot MyBatis升級篇-XML-自增ID

15、Spring Boot MyBatis升級篇-XML-增刪改查

16、Spring Boot MyBatis升級篇-XML-分頁查詢

17、Spring Boot MyBatis升級篇-XML-分頁PageHelper不生效

18、Spring Boot MyBatis升級篇-XML-動態SQL(if test)

19、Spring Boot MyBatis升級篇-XML-註解-初嘗試

20、Spring Boot MyBatis升級篇- pagehelper替換為pagehelper-spring-boot-starter

第八章 Spring Boot 知識點1

1、Spring Boot 攔截器HandlerInterceptor

2、Spring Boot啟動載入資料CommandLineRunner

3、Spring Boot環境變數讀取和屬性物件的繫結

4、Spring Boot使用自定義的properties

5、Spring Boot使用自定義的properties

6、Spring Boot使用@SpringBootApplication

7、Spring Boot 監控和管理生產環境

第十章 Spring Boot 打包部署

1、Spring Boot打包部署((提供Linux的sh檔案))

第十一章 Spring Boot 日誌

1、spring boot日誌—理論

2、Spring Boot日誌-logback

3、Spring Boot日誌-log4j2


相關推薦

43. Spring Boot動態資料來源資料來源自動切換開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

29. Spring boot 檔案檔案開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

Spring boot 檔案檔案開始Spring Boot

檔案上傳主要分以下幾個步驟: (1)新建maven java project; (2)在pom.xml加入相應依賴; (3)新建一個表單頁面(這裡使用thymeleaf); (4)編寫controller; (5)測試; (6)對上傳的檔案做一些限制; (7)多檔案上傳

40. springboot + devtools熱部署開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

16. Spring Boot使用Druid程式設計注入開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

51. spring boot屬性檔案環境配置開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

資料新增非同步解析重新整理大資料量redis ——(三)Spring Boot普通類呼叫bean開始Spring Boot

部落格分類:  從零開始學Spring Boot 從零開始學Spring BootSpring Boot普通類呼叫bean    【視訊&交流平臺】 à SpringBoot視訊 http://stu

33Spring Boot 監控和管理生產環境開始Spring Boot

spring-boot-actuator模組提供了一個監控和管理生產環境的模組,可以使用http、jmx、ssh、telnet等拉管理和監控應用。審計(Auditing)、 健康(health)、資料採集(metrics gathering)會自動加入到應用裡面。 首先,寫

27Spring Boot Junit單元測試開始Spring Boot

Junit這種老技術,現在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在專案中的重要性。 那麼先簡單說一下為什麼要寫測試用例 1. 可以避免測試點的遺漏,為了更好的進行測試,可以提高測試效率 2. 可以自動測試,可以在專案打包前進行測試校驗 3. 可以及時發現因為

4Spring Boot完美使用FastJson解析JSON資料開始Spring Boot

個人使用比較習慣的json框架是fastjson,所以spring boot預設的json使用起來就很陌生了,所以很自然我就想我能不能使用fastjson進行json解析呢? 引入fastjson依賴庫:   <dependencies>         <

19Spring Boot 新增JSP支援開始Spring Boot

【來也匆匆,去也匆匆,在此留下您的腳印吧,轉發點贊評論;       您的認可是我最大的動力,感謝您的支援】 看完本文章您可能會有些疑問,可以檢視之後的一篇部落格: ----------------------------------------------------

3Spring Boot熱部署開始Spring Boot

在編寫程式碼的時候,你會發現我們只是簡單把列印資訊改變了下,就需要重新部署,如果是這樣的編碼方式,那麼我們估計一天下來之後就真的是打幾個Hello World之後就下班了。那麼如何解決熱部署的問題呢?那就是springloaded,加入如下配置: <plugin>

53. spring boot系列合集開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

Spring Boot使用模板freemarker開始Spring Boot(轉)

dep demo attach macro 使用 doctype com 地址 2016年 視頻&交流平臺:à SpringBoot網易雲課堂視頻http://study.163.com/course/introduction.htm?courseId=10

33. Spring Boot 監控和管理生產環境開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

8. 使用JPA儲存資料開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

103. Spring Boot Freemarker特別篇之contextPath開始Spring Boot

需求緣起:有人在群裡@我:請教群主大神一個問題,spring boot  + freemarker 怎麼獲取contextPath 頭疼死我了,網上沒一個靠譜的 。我就看看之前部落格中的 【Spring Boot使用模板freemarker】好像確實沒有介紹到在.ftl檔案

31. Spring Boot匯入XML配置開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

2. Spring Boot返回json資料開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000

35. Spring Boot整合Redis實現快取機制開始Spring Boot

【視訊&交流平臺】 http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=40000000