温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何利用Java上传大文件

发布时间:2020-11-09 17:28:16 来源:亿速云 阅读:655 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关如何利用Java上传大文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Java大文件上传详解

前言:

上周遇到这样一个问题,客户上传高清视频(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;  
}

看完上述内容,你们对如何利用Java上传大文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI