首页 文章详情

java解决上传文件接口文件过大页面崩溃

彭培阳 | 644 2022-03-15 09:42 0 0 0
UniSMS (合一短信)

不能直接用流读写文件,文件太大会使内存不足,使用缓存循环读写



for (Map.Entry<String, MultipartFile> me : fileMap.entrySet()) {

MultipartFile file = me.getValue();
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);
//判断目标文件所在的目录是否存在
if (!newFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
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){
//将内存中的数据写入磁盘
}


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter