Spring Boot實(shí)現(xiàn)文件上傳示例代碼
使用SpringBoot進(jìn)行文件上傳的方法和SpringMVC差不多,本文單獨(dú)新建一個(gè)最簡(jiǎn)單的DEMO來(lái)說(shuō)明一下。
主要步驟包括:
1、創(chuàng)建一個(gè)springboot項(xiàng)目工程,本例名稱(demo-uploadfile)。
2、配置 pom.xml 依賴。
3、創(chuàng)建和編寫文件上傳的 Controller(包含單文件上傳和多文件上傳)。
4、創(chuàng)建和編寫文件上傳的 HTML 測(cè)試頁(yè)面。
5、文件上傳相關(guān)限制的配置(可選)。
6、運(yùn)行測(cè)試。
項(xiàng)目工程截圖如下:

文件代碼:
<dependencies>
<!-- spring boot web支持 -->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
package com.example.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
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 org.springframework.web.multipart.MultipartHttpServletRequest;
/**
* 文件上傳的Controller
*
* @author 單紅宇(CSDN CATOOP)
* @create 2017年3月11日
*/
@Controller
public class FileUploadController {
// 訪問(wèn)路徑為:http://ip:port/upload
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String upload() {
return "/fileupload";
}
// 訪問(wèn)路徑為:http://ip:port/upload/batch
@RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
public String batchUpload() {
return "/mutifileupload";
}
/**
* 文件上傳具體實(shí)現(xiàn)方法(單文件上傳)
*
* @param file
* @return
*
* @author 單紅宇(CSDN CATOOP)
* @create 2017年3月11日
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 這里只是簡(jiǎn)單例子,文件直接輸出到項(xiàng)目路徑下。
// 實(shí)際項(xiàng)目中,文件需要輸出到指定位置,需要在增加代碼處理。
// 還有關(guān)于文件格式限制、文件大小限制,詳見(jiàn):中配置。
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 "上傳失敗,因?yàn)槲募强盏?";
}
}
/**
* 多文件上傳 主要是使用了MultipartHttpServletRequest和MultipartFile
*
* @param request
* @return
*
* @author 單紅宇(CSDN CATOOP)
* @create 2017年3月11日
*/
@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
public @ResponseBody String batchUpload(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";
}
}
package com.example.configuration;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
/**
* 文件上傳配置
*
* @author 單紅宇(CSDN CATOOP)
* @create 2017年3月11日
*/
public class FileUploadConfiguration {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 設(shè)置文件大小限制 ,超出設(shè)置頁(yè)面會(huì)拋出異常信息,
// 這樣在文件上傳的地方就需要進(jìn)行異常信息的處理了;
factory.setMaxFileSize("256KB"); // KB,MB
/// 設(shè)置總上傳數(shù)據(jù)總大小
factory.setMaxRequestSize("512KB");
// Sets the directory location where files will be stored.
// factory.setLocation("路徑地址");
return factory.createMultipartConfig();
}
}
@SpringBootApplication
public class DemoUploadfileApplication {
public static void main(String[] args) {
SpringApplication.run(DemoUploadfileApplication.class, args);
}
}
<!DOCTYPE html>
<html>
<head>
<title>文件上傳示例</title>
</head>
<body>
<h2>文件上傳示例</h2>
<hr/>
<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>
<!DOCTYPE html>
<html>
<head>
<title>批量文件上傳示例</title>
</head>
<body>
<h2>批量文件上傳示例</h2>
<hr/>
<form method="POST" enctype="multipart/form-data"
action="/upload/batch">
<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>
最后啟動(dòng)服務(wù),訪問(wèn) http://localhost:8080/upload 和 http://localhost:8080/upload/batch 測(cè)試文件上傳。
Demo源代碼下載地址:uploadfile_jb51.rar
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Windows同時(shí)配置兩個(gè)jdk環(huán)境變量的操作步驟
Java Development Kit (JDK) 是開(kāi)發(fā)Java應(yīng)用程序的基礎(chǔ),包含了編譯器、調(diào)試器以及其他必要的工具,本指南將一步步指導(dǎo)您完成在Windows操作系統(tǒng)上同時(shí)配置兩個(gè)jdk環(huán)境變量的操作步驟,需要的朋友可以參考下2024-09-09
SpringMVC接收復(fù)雜集合對(duì)象(參數(shù))代碼示例
這篇文章主要介紹了SpringMVC接收復(fù)雜集合對(duì)象(參數(shù))代碼示例,舉接收List<String>、List<User>、List<Map<String,Object>>、User[]、User(bean里面包含List)幾種較為復(fù)雜的集合參數(shù),具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
Spring Bean實(shí)例化實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Spring Bean實(shí)例化實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫(kù)遷移的實(shí)現(xiàn)示例
Flyway是一個(gè)數(shù)據(jù)庫(kù)遷移工具,它提供遷移歷史和回滾的功能,本文主要介紹了如何使用Flyway來(lái)管理Spring Boot應(yīng)用程序中的SQL數(shù)據(jù)庫(kù)架構(gòu),感興趣的可以了解一下2023-08-08
Java?Web?Axios實(shí)現(xiàn)前后端數(shù)據(jù)異步交互實(shí)例代碼
Axios作為一個(gè)流行的前端?HTTP?通信庫(kù),可以極大地簡(jiǎn)化前端與后端之間的數(shù)據(jù)交互,這篇文章主要介紹了Java?Web?Axios實(shí)現(xiàn)前后端數(shù)據(jù)異步交互的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-09-09
SpringBoot中并發(fā)定時(shí)任務(wù)的實(shí)現(xiàn)、動(dòng)態(tài)定時(shí)任務(wù)的實(shí)現(xiàn)(看這一篇就夠了)推薦
這篇文章主要介紹了SpringBoot并發(fā)定時(shí)任務(wù)動(dòng)態(tài)定時(shí)任務(wù)實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

