SpringBoot文件上傳的幾種常見方式(單文件上傳、多文件上傳)
文件上傳功能在很多系統(tǒng)中都占據(jù)非常重要的份置,軟件開發(fā)人員在實現(xiàn)文件上傳時,除了需要確保程序代碼的穩(wěn)健性和高維護性外,還需要從社會責任的角度審的需求,秉承合法、合規(guī)的職業(yè)理念進行數(shù)據(jù)讀寫,避免程序在保存用戶上傳的文件時造成不良的社會影響。例如,應該關(guān)注保護用戶的隱私,避免用戶的隱私泄露,以及杜絕上傳非法文件。
文件上傳的常見場景
在日常開發(fā)中,文件上傳的場景多種多樣。比如,在線教育平臺上的視頻資源上傳,社交平臺上的圖片分享,以及企業(yè)內(nèi)部的知識文檔管理等。這些場景對文件上傳的要求也各不相同,有的追求速度,有的注重穩(wěn)定性,還有的需要考慮文件大小和安全性。因此,針對不同需求,我們有了秒傳、斷點續(xù)傳和分片上傳等解決方案。
文件上傳是一個常見的需求。例如社交平臺用戶上傳頭像、電商系統(tǒng)商家上傳商品圖片、文檔管理系統(tǒng)用戶上傳資料等都會用到。本文詳細介紹SpringBoot關(guān)于單文件上傳、多文件上傳以及限制文件大小和類型等幾種常見方式。
1. 單文件上傳
單文件上傳是最基礎的文件上傳場景,當用戶選擇一個文件并提交到服務器,可以使用 MultipartFile 類型來接收上傳的文件。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class SingleFileUploadController {
@PostMapping("/singleFileUpload")
@ResponseBody
public String singleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "請選擇要上傳的文件";
}
try {
// 獲取文件名
String fileName = file.getOriginalFilename();
// 定義文件存儲路徑
String filePath = "uploads/";
File dest = new File(filePath + fileName);
// 檢查目錄是否存在,不存在則創(chuàng)建
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 保存文件
file.transferTo(dest);
return "文件上傳成功";
} catch (IOException e) {
e.printStackTrace();
return "文件上傳失敗";
}
}
}index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>單文件上傳</title>
</head>
<body>
<form action="/singleFileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上傳">
</form>
</body>
</html>enctype="multipart/form-data"是必須的
2. 多文件上傳
多文件上傳允許用戶一次選擇多個文件進行上傳??梢允褂?MultipartFile 數(shù)組來接收多個上傳的文件。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class MultipleFileUploadController {
@PostMapping("/multipleFileUpload")
@ResponseBody
public String multipleFileUpload(@RequestParam("files") MultipartFile[] files) {
if (files.length == 0) {
return "請選擇要上傳的文件";
}
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue;
}
try {
String fileName = file.getOriginalFilename();
String filePath = "uploads/";
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
return "文件上傳失敗";
}
}
return "文件上傳成功";
}
}index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多文件上傳</title>
</head>
<body>
<form action="/multipleFileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<input type="submit" value="上傳">
</form>
</body>
</html>input組件需要 multiple 支持多文件選擇
3. 限制文件大小和類型
在實際開發(fā)的時候,可能需要對上傳的文件大小和類型進行限制??梢酝ㄟ^配置SpringBoot的 MultipartConfigElement 來實現(xiàn)文件大小限制,同時在代碼中檢查文件類型。
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 單個文件最大10MB
factory.setMaxFileSize(DataSize.ofMegabytes(10));
// 設置總上傳數(shù)據(jù)總大小20MB
factory.setMaxRequestSize(DataSize.ofMegabytes(20));
return factory.createMultipartConfig();
}
}檢查文件類型:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class FileUploadWithLimitController {
@PostMapping("/fileUploadWithLimit")
@ResponseBody
public String fileUploadWithLimit(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "請選擇要上傳的文件";
}
// 檢查文件類型
String contentType = file.getContentType();
if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
return "只允許上傳jpeg和png格式文件";
}
try {
String fileName = file.getOriginalFilename();
String filePath = "uploads/";
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return "文件上傳成功";
} catch (IOException e) {
e.printStackTrace();
return "文件上傳失敗";
}
}
}getContentType 方法可以獲取文件的MIME類型
到此這篇關(guān)于SpringBoot實戰(zhàn)——文件上傳一篇搞定的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Activiti7與Spring以及Spring Boot整合開發(fā)
這篇文章主要介紹了Activiti7與Spring以及Spring Boot整合開發(fā),在Activiti中核心類的是ProcessEngine流程引擎,與Spring整合就是讓Spring來管理ProcessEngine,有感興趣的同學可以參考閱讀2023-03-03
Java中將UUID存儲為Base64字符串的方法實現(xiàn)
使用Base64編碼來對UUID存儲在一些特定的場合被廣泛的使用,本文主要介紹了Java中將UUID存儲為Base64字符串的方法實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-04-04
Java中利用Alibaba開源技術(shù)EasyExcel來操作Excel表的示例代碼
這篇文章主要介紹了Java中利用Alibaba開源技術(shù)EasyExcel來操作Excel表的示例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
使用IDEA對SpringBoot應用進行遠程調(diào)試方式
文章介紹了如何在IDEA中對部署在服務器上的SpringBoot應用進行遠程調(diào)試,通過配置遠程調(diào)試端口和啟動參數(shù),本地IDEA可以設置斷點并進行調(diào)試2025-02-02
Java實現(xiàn)SMS短信通發(fā)送手機驗證碼案例講解
這篇文章主要介紹了Java實現(xiàn)SMS短信通發(fā)送手機驗證碼案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
Spring Boot Starter 的應用場景與自動配置方式
本文介紹了Spring Boot Starter的使用場景,如何自定義Starter以及Spring Boot自動配置原理,Spring Boot Starter解決了依賴導入和配置繁瑣的問題,通過自動配置類和xxxProperties類實現(xiàn)組件的自動注入和配置,感興趣的朋友一起看看吧2025-03-03

