Spring boot實現(xiàn)文件上傳實例(多文件上傳)
文件上傳主要分以下幾個步驟:
(1)新建maven java project;
(2)在pom.xml加入相應(yīng)依賴;
(3)新建一個表單頁面(這里使用thymleaf);
(4)編寫controller;
(5)測試;
(6)對上傳的文件做一些限制;
(7)多文件上傳實現(xiàn)
(1)新建maven Java project
新建一個名稱為spring-boot-fileupload maven Java項目;
(2)在pom.xml加入相應(yīng)依賴;
加入相應(yīng)的maven依賴,具體看以下解釋:
<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.example</groupId>
<artifactId>spring-boot-fileupload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!--
spring boot 父節(jié)點依賴,
引入這個之后相關(guān)的引入就不需要添加version配置,
spring boot會自動選擇最合適的版本進(jìn)行添加。
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.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.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(3)新建一個表單頁面(這里使用thymleaf)
在src/main/resouces新建templates,在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進(jìn)行測試,這里主要實現(xiàn)兩個方法:其一就是提供訪問的/file路徑;其二就是提供post上傳的/upload方法,具體看代碼實現(xiàn):
@Controller
public class FileUploadController {
// 訪問路徑為:http://127.0.0.1:8080/file
@RequestMapping("/file")
public String file() {
return "/file";
}
/**
* 文件上傳具體實現(xiàn)方法;
*
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
/*
* 這段代碼執(zhí)行完畢之后,圖片上傳到了工程的跟路徑; 大家自己擴散下思維,如果我們想把圖片上傳到
* d:/files大家是否能實現(xiàn)呢? 等等;
* 這里只是簡單一個例子,請自行參考,融入到實際中可能需要大家自己做一些思考,比如: 1、文件路徑; 2、文件名;
* 3、文件格式; 4、文件大小的限制;
*/
BufferedOutputStream out = new BufferedOutputStream(
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 "上傳失敗,因為文件是空的.";
}
}
// 訪問路徑為:http://127.0.0.1:8080/file
@RequestMapping("/mutifile")
public String mutifile() {
return "/mutifile";
}
(5)編寫Application.java然后測試
Application沒什么代碼,就是Spring Boot的啟動配置,具體如下:
package com.example.controller;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后你就可以訪問:http://127.0.0.1:8080/file 進(jìn)行測試了,文件上傳的路徑是在工程的跟路徑下,請刷新查看,其它的請查看代碼中的注釋進(jìn)行自行思考
(6)對上傳的文件做一些限制;
對文件做一些限制是有必要的,在Application.java進(jìn)行編碼配置:。
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//// 設(shè)置文件大小限制 ,超了,頁面會拋出異常信息,這時候就需要進(jìn)行異常信息的處理了;
factory.setMaxFileSize("128KB"); //KB,MB
/// 設(shè)置總上傳數(shù)據(jù)總大小
factory.setMaxRequestSize("256KB");
//Sets the directory location where files will be stored.
//factory.setLocation("路徑地址");
return factory.createMultipartConfig();
}
(7)多文件上傳實現(xiàn)
多文件對于前段頁面比較簡單,具體代碼實現(xiàn):
在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>
FileUploadController中新增兩個方法:
// 訪問路徑為:http://127.0.0.1:8080/mutifile
@RequestMapping("/mutifile")
public String mutifile() {
return "/mutifile";
}
/**
* 多文件具體上傳時間,主要是使用了MultipartHttpServletRequest和MultipartFile
*
* @param request
* @return
*/
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
@ResponseBody
public 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 = new BufferedOutputStream(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
+ " because the file was empty.";
}
}
return "upload successful";
}
訪問路徑:http://127.0.0.1:8080/mutifile 進(jìn)行測試。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot設(shè)置統(tǒng)一的返回格式的方法步驟
在我們應(yīng)用中我們通常與前端交互使用json格式,設(shè)置統(tǒng)一的返回json 格式是非常必要的,本文主要介紹了Springboot設(shè)置統(tǒng)一的返回格式的方法步驟,具有一定的參考價值,感興趣的可以了解一下2024-01-01
Java導(dǎo)出Execl疑難點處理的實現(xiàn)
這篇文章主要介紹了Java導(dǎo)出Execl疑難點處理的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
MyBatis中map的應(yīng)用與模糊查詢實現(xiàn)代碼
這篇文章主要介紹了MyBatis中map的應(yīng)用與模糊查詢實現(xiàn)代碼,文中通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-11-11
Mybatis框架之模板方法模式(Template Method Pattern)的實現(xiàn)
MyBatis中使用了模板方法模式來控制SQL語句的執(zhí)行流程,本文主要介紹了Mybatis框架之模板方法模式(Template Method Pattern)的實現(xiàn),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
jmeter實現(xiàn)接口關(guān)聯(lián)的兩種方式(正則表達(dá)式提取器和json提取器)
Jmeter用于接口測試時,后一個接口經(jīng)常需要用到前一次接口返回的結(jié)果,本文主要介紹了jmeter實現(xiàn)接口關(guān)聯(lián)的兩種方式,感興趣的小伙伴們可以參考一下2021-11-11

