一文徹底弄懂Java中MultipartFile接口和File類
一、File類
java.io.File是 Java 標(biāo)準(zhǔn)庫中用于操作文件和目錄路徑的類。它提供了很多方法,用于創(chuàng)建、刪除、重命名、判斷文件是否存在、獲取文件信息等操作。
獲取文件信息
boolean exists(): 判斷文件或目錄是否存在。boolean isFile(): 判斷是否是文件。boolean isDirectory(): 判斷是否是目錄。String getName(): 獲取文件或目錄的名稱。String getPath(): 獲取文件或目錄的路徑。String getAbsolutePath(): 獲取文件或目錄的絕對(duì)路徑。long length(): 獲取文件的大小(字節(jié)數(shù))。
文件和目錄操作
boolean createNewFile(): 創(chuàng)建新文件。如果文件已存在,則不創(chuàng)建,返回false。boolean mkdir(): 創(chuàng)建新目錄。如果目錄已存在,則不創(chuàng)建,返回false。boolean mkdirs(): 創(chuàng)建新目錄及其父目錄,如果不存在的話。boolean delete(): 刪除文件或目錄。
文件路徑操作
boolean renameTo(File dest): 重命名文件或目錄。如果成功,返回true;否則,返回false。String[] list(): 返回目錄下的文件和目錄名數(shù)組。File[] listFiles(): 返回目錄下的文件和目錄的File對(duì)象數(shù)組。
文件過濾
String[] list(FilenameFilter filter): 返回目錄下滿足指定過濾器條件的文件和目錄名數(shù)組。File[] listFiles(FileFilter filter): 返回目錄下滿足指定過濾器條件的文件和目錄的File對(duì)象數(shù)組。
二、MultipartFile接口
MultipartFile是 Spring 框架提供的一個(gè)接口,用于表示處理文件上傳的對(duì)象。它通常用于處理multipart/form-data類型的請(qǐng)求,例如處理文件上傳的表單。首先我們依舊可以通過源碼的學(xué)習(xí)來進(jìn)一步了解這個(gè)接口。
2.1 源碼和方法功能
public interface MultipartFile extends InputStreamSource {
String getName();
@Nullable
String getOriginalFilename();
@Nullable
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
InputStream getInputStream() throws IOException;
default Resource getResource() {
return new MultipartFileResource(this);
}
void transferTo(File dest) throws IOException, IllegalStateException;
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
}
- String getName():獲取上傳文件的表單字段名稱
- String getOriginalFilename():獲取上傳文件的原始文件名
- String getContentType():獲取上傳文件的內(nèi)容類型
- boolean isEmpty():判斷上傳文件是否為空
- long getSize():獲取上傳文件的大小,單位是字節(jié)
- byte[] getBytes() throws IOException:獲取上傳文件的字節(jié)數(shù)組表示
- InputStream getInputStream() throws IOException:獲取上傳文件的輸入流
- default Resource getResource() :將
MultipartFile封裝成了Resource對(duì)象,從而可以使用Resource接口提供的方法來操作上傳文件的內(nèi)容。 - void transferTo(File dest) throws IOException, IllegalStateException:將上傳文件保存到指定的文件;
- default void transferTo(Path dest) throws IOException, IllegalStateException :將上傳文件保存在指定的路徑下;
2.2 void transferTo(File dest)
前面我們已經(jīng)介紹了該方法是Spring中提供的將上傳文件保存到指定的文件中的抽象方法,溯源源碼我們可以看到這個(gè)接口方法被三個(gè)實(shí)現(xiàn)類實(shí)現(xiàn)了,分別是CommonsMultipartFile、MockMultipartFile 和 StandardMultipartHttpServletRequest。
CommonsMultipartFile中的方法體
我們可以看到CommonsMultipartFile中的方法體主要是通過檢測(cè)傳進(jìn)來的文件是否可用、是否存在,并在檢測(cè)完成就執(zhí)行寫入的操作
public void transferTo(File dest) throws IOException, IllegalStateException {
if (!this.isAvailable()) {
throw new IllegalStateException("File has already been moved - cannot be transferred again");
} else if (dest.exists() && !dest.delete()) {
throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
} else {
try {
this.fileItem.write(dest);
LogFormatUtils.traceDebug(logger, (traceOn) -> {
String action = "transferred";
if (!this.fileItem.isInMemory()) {
action = this.isAvailable() ? "copied" : "moved";
}
return "Part '" + this.getName() + "', filename '" + this.getOriginalFilename() + "'" + (traceOn ? ", stored " + this.getStorageDescription() : "") + ": " + action + " to [" + dest.getAbsolutePath() + "]";
});
} catch (FileUploadException var3) {
throw new IllegalStateException(var3.getMessage(), var3);
} catch (IOException | IllegalStateException var4) {
throw var4;
} catch (Exception var5) {
throw new IOException("File transfer failed", var5);
}
}
}上面這段demo中可能對(duì)于this.isAvailable()有疑問,我們知曉這里的this其實(shí)是該類的實(shí)例化對(duì)象,但是這里的this.isAvailable()就是拿來判斷目的文件是否可用,調(diào)用的就是類的內(nèi)部方法,判斷是否可用的條件就是該目標(biāo)文件是否被加載進(jìn)內(nèi)存中!

這里給出一個(gè)使用該方法的例子,需要注意的是這時(shí)候方法要求的是一個(gè)目標(biāo)File對(duì)象,我們需要在調(diào)用該目標(biāo)方法的時(shí)候就根據(jù)目標(biāo)路徑創(chuàng)建了目標(biāo)的File對(duì)象。
// 獲取上傳文件的原始文件名
String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
// 構(gòu)建目標(biāo)文件對(duì)象
File destFile = new File("/path/to/destination/directory", originalFilename);
try {
// 將上傳文件保存到目標(biāo)文件
file.transferTo(destFile);
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "Failed to upload the file.";
}StandardMultipartHttpServletRequest實(shí)現(xiàn)類
而另一個(gè)實(shí)現(xiàn)類StandardMultipartHttpServletRequest和CommonsMultipartFile的區(qū)別就在于使用StandardMultipartHttpServletRequest直接上傳文件的話可能會(huì)出現(xiàn)目錄跳躍的問題,而CommonsMultipartFile不會(huì),這是因?yàn)槠鋵?duì)路勁分隔符了相關(guān)的限制,具體的部分大家可以看看這篇博客:http://m.fzitv.net/program/3053831or.htm 而MockMultipartFile這個(gè)實(shí)現(xiàn)類就更簡(jiǎn)單了,做了簡(jiǎn)單的輸入輸出流的copy,這里就不再水字?jǐn)?shù)了。

2.3 default void transferTo(Path dest)
該默認(rèn)方法在實(shí)現(xiàn)類中被重寫了,但主要的功能還是不變,就是將上傳的文件寫入到指定路徑的Path對(duì)象中實(shí)現(xiàn)文件上傳的功能。
這里給出使用的示例代碼:
// 構(gòu)建目標(biāo)文件路徑
String uploadDirectory = "/path/to/destination/directory";
String originalFilename = file.getOriginalFilename();
Path filePath = Paths.get(uploadDirectory, originalFilename);
try {
// 將上傳文件保存到目標(biāo)文件
file.transferTo(filePath);
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "Failed to upload the file.";
}總結(jié)
這篇文章主要圍繞MultipartFile接口和File類中相關(guān)方法的功能進(jìn)行梳理,其中有關(guān)文件寫入File對(duì)象和Path對(duì)象重點(diǎn)進(jìn)行了剖析,而具體的有關(guān)文件管理的部分知識(shí)大家可以關(guān)注后續(xù)荔枝梳理的有關(guān)SpringBoot整合MinIO的博客和后續(xù)的博文輸出。
到此這篇關(guān)于Java中MultipartFile接口和File類的文章就介紹到這了,更多相關(guān)Java MultipartFile接口和File類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)雙鏈表互相交換任意兩個(gè)節(jié)點(diǎn)的方法示例
這篇文章主要介紹了Java實(shí)現(xiàn)雙鏈表互相交換任意兩個(gè)節(jié)點(diǎn)的方法,簡(jiǎn)單講述了雙鏈表的概念,并結(jié)合實(shí)例形式給出了java雙鏈表實(shí)現(xiàn)任意兩個(gè)節(jié)點(diǎn)交換的操作技巧,需要的朋友可以參考下2017-11-11
java設(shè)計(jì)模式—靜態(tài)代理模式(聚合與繼承方式對(duì)比)
下面小編就為大家?guī)硪黄猨ava設(shè)計(jì)模式—靜態(tài)代理模式(聚合與繼承方式對(duì)比)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05
解決Java變異出現(xiàn)錯(cuò)誤No enclosing instance of type XXX is accessible
這牌你文章主要給大家分享解決Java變異出現(xiàn)錯(cuò)誤,具體的饑餓絕方案請(qǐng)看下面文章的內(nèi)容,需要的朋友可以參考一下,希望能幫助到你2021-09-09
Java簡(jiǎn)單實(shí)現(xiàn)定時(shí)器
這篇文章主要為大家詳細(xì)介紹了Java簡(jiǎn)單實(shí)現(xiàn)定時(shí)器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
SpringBoot如何通過自定義注解實(shí)現(xiàn)權(quán)限檢查詳解
這篇文章主要給大家介紹了關(guān)于SpringBoot如何通過自定義注解實(shí)現(xiàn)權(quán)限檢查的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
SpringBoot設(shè)置Session失效時(shí)間的解決方案
當(dāng)過期時(shí)間是大于1分鐘的時(shí)候是沒有什么問題的,但是如果設(shè)置過期時(shí)間小于1分鐘,就會(huì)失效,這篇文章主要介紹了SpringBoot設(shè)置Session失效時(shí)間的解決方案,需要的朋友可以參考下2024-05-05

