springboot 大文件上传 java.lang.OutOfMemoryError

it2024-12-17  10

错误代码 @PostMapping("/upload") public ResultMsg algorithmFile(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); String[] fileNamePart = fileName.split("\\."); String fileNameWithPath = filePath + UUID.randomUUID().toString(true) + "." + fileNamePart[fileNamePart.length - 1]; try { Files.write(Paths.get(fileNameWithPath), file.getBytes()); } catch (IOException e) { e.printStackTrace(); } return new ResultMsg(ResponseCodeEnum.SUCCESS.getIndex(), fileNameWithPath, "上传成功"); } 正确代码 @PostMapping("/upload") public ResultMsg algorithmFile(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); String[] fileNamePart = fileName.split("\\."); String fileNameWithPath = filePath + UUID.randomUUID().toString(true) + "." + fileNamePart[fileNamePart.length -1]; try { InputStream input = file.getInputStream(); FileOutputStream out = new FileOutputStream(new File(fileNameWithPath)); IOUtils.copy(input, out); out.close(); } catch (IOException e1) { e1.printStackTrace(); } return new ResultMsg(ResponseCodeEnum.SUCCESS.getIndex(), fileNameWithPath, "上传成功"); }

总结

错误代码中使用了,file.getBytes(),应该是该操作导致了内存溢出。具体区别和原因暂时没分析

最新回复(0)