SpringBoot怎么实现web端上传超大文件
上周遇到这样一个问题,客户上传高清视频(1G以上)的时候上传失败。 一开始以为是session过期或者文件大小受系统限制,导致的错误。 查看了系统的配置文件没有看到文件大小限制, web.xml中seesiontimeout是30,我把它改成了120。 但还是不行,有时候10分钟就崩了。 同事说,可能是客户这里服务器网络波动导致网络连接断开,我觉得有点道理。 但是我在本地测试的时候发觉上传也失败,网络原因排除。 看了日志,错误为: 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("文件内容为空"); } return null; } 乍一看没什么大问题,我在 stream.write(bytes); 这句加了断点,发觉根本就没走到。 而是在 bytes = file.getBytes(); 就报错了。 原因应该是文件太大的话,字节数超过Integer(Bytes[]数组)的最大值,导致的问题。 既然这样,把文件一点点的读进来即可。 修改上传代码如下: 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("文件内容为空"); } return null; } 效果展示:
示例下载地址
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2020-04-10 WEB 项目大文件上传下载解决方案
2020-04-10 B/S WEB项目大文件上传下载解决方案
2020-04-10 SpringBoot WEB项目大文件上传下载解决方案
2020-04-10 SpringMVC WEB项目大文件上传下载解决方案
2020-04-10 JSP WEB项目大文件上传下载解决方案
2020-04-10 PHP WEB项目大文件上传下载解决方案
2020-04-10 .NET WEB项目大文件上传下载解决方案