码迷,mamicode.com
首页 > 编程语言 > 详细

Java上传大文件

时间:2017-06-07 12:54:46      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:lock   empty   x11   inf   ble   highlight   lsp   acea   auto   

看了日志,错误为:

1
java.lang.OutOfMemoryError Java heap space

上传文件代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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[]数组)的最大值,导致的问题。

既然这样,把文件一点点的读进来即可。

修改上传代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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://www.2cto.com/kf/201702/596396.html

Java上传大文件

标签:lock   empty   x11   inf   ble   highlight   lsp   acea   auto   

原文地址:http://www.cnblogs.com/yht-817/p/6956173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!