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

彭培阳

共 888字,需浏览 2分钟

 · 2022-03-15

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



for (Map.Entry 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){
//将内存中的数据写入磁盘
}


浏览 126
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报