Read the log, the error is:
| 1 |
java.lang.OutOfMemoryError Java heap space |
Upload the file code as follows:
| 12345678910111213141516171819202122232425262728293031 |
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; } |
At first glance there is no big problem, I am in Stream.Write (bytes); This sentence added a break point, found that there is no way to go. But in bytes = File.getbytes (); It's an error.
The reason should be that the file is too large, the number of bytes exceeds the maximum value of the integer (bytes[] array), causing the problem.
In that case, read the file in a little bit.
Modify the upload code as follows:
| 12345678910111213141516171819202122232425262728293031323334353637 |
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; } |
Transfer from http://www.2cto.com/kf/201702/596396.html
Java Uploading large files