java中File與MultipartFile互轉(zhuǎn)代碼示例
1 概述
當(dāng)我們在處理文件上傳的功能時,通常會使用MultipartFile對象來表示上傳的文件數(shù)據(jù)。然而,有時候我們可能已經(jīng)有了一個File對象,而不是MultipartFile對象,需要將File對象轉(zhuǎn)換為MultipartFile對象進行進一步處理。
在Java中,F(xiàn)ile對象表示文件在本地文件系統(tǒng)中的引用,而MultipartFile對象是Spring框架提供的用于處理文件上傳的接口。MultipartFile接口提供了許多有用的方法,例如獲取文件名、獲取文件內(nèi)容、獲取文件大小等。
2 代碼示例
2.1 引入依賴
<!--File轉(zhuǎn)MultipartFile需要test包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.9.RELEASE</version> <scope>compile</scope> </dependency>
2.2 MultipartFile轉(zhuǎn)File
public static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}2.3 File轉(zhuǎn)MultipartFile
//file 轉(zhuǎn)換為 MultipartFile
private MultipartFile getMulFileByPath(String filePath)
{
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
FileItem item = factory.createItem(textFieldName, "text/plain", true,
"MyFileName" + extFile);
File newfile = new File(filePath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try
{
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192))
!= -1)
{
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
MultipartFile mfile = new CommonsMultipartFile(item);
return mfile;
}總結(jié)
到此這篇關(guān)于java中File與MultipartFile互轉(zhuǎn)的文章就介紹到這了,更多相關(guān)java File與MultipartFile互轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot2.6.x默認(rèn)禁用循環(huán)依賴后的問題解決
由于SpringBoot從底層逐漸引導(dǎo)開發(fā)者書寫規(guī)范的代碼,同時也是個憂傷的消息,循環(huán)依賴的應(yīng)用場景實在是太廣泛了,所以SpringBoot 2.6.x不推薦使用循環(huán)依賴,本文給大家說下SpringBoot2.6.x默認(rèn)禁用循環(huán)依賴后的應(yīng)對策略,感興趣的朋友一起看看吧2022-02-02
java實現(xiàn)找出兩個文件中相同的單詞(兩種方法)
這篇文章主要介紹了java實現(xiàn)找出兩個文件中相同的單詞(兩種方法),需要的朋友可以參考下2020-08-08
關(guān)于SpringCloud?Ribbon替換輪詢算法問題
Spring?Cloud?Ribbon是基于Netlix?Ribbon實現(xiàn)的一套客戶端負(fù)載均衡的工具。接下來通過本文給大家介紹SpringCloud?Ribbon替換輪詢算法問題,需要的朋友可以參考下2022-01-01
spring的構(gòu)造函數(shù)注入屬性@ConstructorBinding用法
這篇文章主要介紹了關(guān)于spring的構(gòu)造函數(shù)注入屬性@ConstructorBinding用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

