首页 > 代码库 > Java上传大文件

Java上传大文件

看了日志,错误为:

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上传大文件