1. 程式人生 > >Java上傳大文件

Java上傳大文件

error dsi ktr word nbsp comment buffer bytes part

看了日誌,錯誤為:

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