java解決上傳文件接口文件過大頁(yè)面崩潰
不能直接用流讀寫文件,文件太大會(huì)使內(nèi)存不足,使用緩存循環(huán)讀寫
for (Map.Entry
String originalFilename = file.getOriginalFilename();
//新的文件名稱
String newFileName = res + originalFilename.substring(originalFilename.lastIndexOf('.'));
String rootPath = upPath + File.separator + dateDirs + File.separator + newFileName;
//新文件
File newFile = new File(rootPath);
//判斷目標(biāo)文件所在的目錄是否存在
if (!newFile.getParentFile().exists()) {
//如果目標(biāo)文件所在的目錄不存在,則創(chuàng)建父目錄
newFile.getParentFile().mkdirs();
}
try(
InputStream in = file.getInputStream();
FileOutputStream fos = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);){
int b=-1;
byte[]buffer = new byte[1024];
while ((b=in.read(buffer))!=-1){
bos.write(buffer,0,b);
}
}catch (Exception e){
//將內(nèi)存中的數(shù)據(jù)寫入磁盤
}
評(píng)論
圖片
表情
