Spring boot 檔案上傳(多檔案上傳)【從零開始學Spring Boot】
檔案上傳主要分以下幾個步驟:
(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>
</
<dependencies>
<!-- spring boot web支援:mvc,aop... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</
<!-- 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
public class 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")MultipartFile file){
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(FileNotFoundException e) {
e.printStackTrace();
return "上傳失敗,"+e.getMessage();
}catch (IOException e) {
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
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
進行測試了,檔案上傳的路徑是在工程的跟路徑下,請重新整理檢視,其它的請檢視程式碼中的註釋進行自行思考。
(6)對上傳的檔案做一些限制;
對檔案做一些限制是有必要的,在App.java進行編碼配置:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = newMultipartConfigFactory();
//// 設定檔案大小限制 ,超了,頁面會丟擲異常資訊,這時候就需要進行異常資訊的處理了;
factory.setMaxFileSize("128KB"); //KB,MB
/// 設定總上傳資料總大小
factory.setMaxRequestSize("256KB");
//Sets the directory location wherefiles will be stored.
//factory.setLocation("路徑地址");
return factory.createMultipartConfig();
}
(7)多檔案上傳實現
多檔案對於前段頁面比較簡單,具體程式碼實現:
在src/resouces/templates/mutifile.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="/batch/upload">
<p>檔案1:<input type="file"name="file" /></p>
<p>檔案2:<input type="file"name="file" /></p>
<p>檔案3:<input type="file"name="file" /></p>
<p><input type="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(HttpServletRequest request){
List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i =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 (Exception e) {
stream = null;
return "You failed to upload " + i + " =>" + e.getMessage();
}
} else {
return "You failed to upload " + i + " becausethe file was empty.";
}
}
return "upload successful";
}