Java大文件上傳詳解及實例代碼
Java大文件上傳詳解
前言:
上周遇到這樣一個問題,客戶上傳高清視頻(1G以上)的時候上傳失敗。
一開始以為是session過期或者文件大小受系統(tǒng)限制,導(dǎo)致的錯誤。查看了系統(tǒng)的配置文件沒有看到文件大小限制,web.xml中seesiontimeout是30,我把它改成了120。但還是不行,有時候10分鐘就崩了。
同事說,可能是客戶這里服務(wù)器網(wǎng)絡(luò)波動導(dǎo)致網(wǎng)絡(luò)連接斷開,我覺得有點道理。但是我在本地測試的時候發(fā)覺上傳也失敗,網(wǎng)絡(luò)原因排除。
看了日志,錯誤為:
java.lang.OutOfMemoryError Java heap space
上傳文件代碼如下:
public static String uploadSingleFile(String path,MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes;
try {
bytes = file.getBytes();
// Create the file on server
File serverFile = createServerFile(path,file.getOriginalFilename());
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.flush();
stream.close();
logger.info("Server File Location="
+ serverFile.getAbsolutePath());
return getRelativePathFromUploadDir(serverFile).replaceAll("\\\\", "/");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}else{
System.out.println("文件內(nèi)容為空");
}
return null;
}
乍一看沒什么大問題,我在 stream.write(bytes); 這句加了斷點,發(fā)覺根本就沒走到。而是在 bytes = file.getBytes(); 就報錯了。
原因應(yīng)該是文件太大的話,字節(jié)數(shù)超過Integer(Bytes[]數(shù)組)的最大值,導(dǎo)致的問題。
既然這樣,把文件一點點的讀進來即可。
修改上傳代碼如下:
public static String uploadSingleFile(String path,MultipartFile file) {
if (!file.isEmpty()) {
//byte[] bytes;
try {
//bytes = file.getBytes();
// Create the file on server
File serverFile = createServerFile(path,file.getOriginalFilename());
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
int length=0;
byte[] buffer = new byte[1024];
InputStream inputStream = file.getInputStream();
while ((length = inputStream.read(buffer)) != -1) {
stream.write(buffer, 0, length);
}
//stream.write(bytes);
stream.flush();
stream.close();
logger.info("Server File Location="
+ serverFile.getAbsolutePath());
return getRelativePathFromUploadDir(serverFile).replaceAll("\\\\", "/");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}else{
System.out.println("文件內(nèi)容為空");
}
return null;
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
據(jù)說這個是可以擼到2089年的idea2020.2(推薦)
這篇文章主要介紹了據(jù)說這個是可以擼到2089年的idea2020.2,本教程給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
Java數(shù)據(jù)結(jié)構(gòu)之循環(huán)隊列簡單定義與用法示例
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之循環(huán)隊列簡單定義與用法,簡要描述了循環(huán)隊列的概念、原理,并結(jié)合實例形式分析了java循環(huán)隊列的定義與使用方法,需要的朋友可以參考下2017-10-10
RxJava+Retrofit+Mvp實現(xiàn)購物車
這篇文章主要為大家詳細(xì)介紹了RxJava+Retrofit+Mvp實現(xiàn)購物車功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
詳解SpringBoot如何優(yōu)雅的進行測試打包部署
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何優(yōu)雅的進行測試打包部署,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12
Java中double數(shù)值保留兩位小數(shù)的4種實現(xiàn)方式舉例
在Java編程中,我們經(jīng)常遇到需要對double類型的浮點數(shù)進行精確截斷或四舍五入保留兩位小數(shù)的需求,這篇文章主要給大家介紹了關(guān)于Java中double數(shù)值保留兩位小數(shù)的4種實現(xiàn)方式,需要的朋友可以參考下2024-07-07

