java http大文件断点续传分片上传
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java http大文件断点续传分片上传,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2202字,纯文字阅读大概需要4分钟。
内容图文
上周遇到这样一个问题,客户上传高清视频(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; } 效果展示:
详细代码可以参考一下这篇文章:http://blog.ncmem.com/wordpress/2019/08/09/java%e5%a4%a7%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0/
原文:https://www.cnblogs.com/songsu/p/13042329.html
内容总结
以上是互联网集市为您收集整理的java http大文件断点续传分片上传全部内容,希望文章能够帮你解决java http大文件断点续传分片上传所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。