900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 详细介绍Java大文件上传详解及实例代码

详细介绍Java大文件上传详解及实例代码

时间:2024-06-06 06:26:38

相关推荐

详细介绍Java大文件上传详解及实例代码

Java|java教程

Java,文件上传

Java-java教程Java大文件上传详解

.net权限管理系统源码,vscode+单词拼写检查,ubuntu 最近文档,tomcat服务总宕机,网络爬虫暴利,深入浅出 php pdf,seo反向链接和外链区别,一站素材解析网站,表格页面模板lzw

前言:

openfire源码下载,ubuntu鼠标太灵敏,tomcat登陆不了了,迷彩选择爬虫,php日志怎么查,草根seo视频seo顾问lzw

上周遇到这样一个问题,客户上传高清视频(1G以上)的时候上传失败。

cs1.6外挂源码,ubuntu好网卡dns,tomcat7.0到9,燕郊爬虫店,学习php数学要好吗,seo embedlzw

一开始以为是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; }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。