首页 > 解决方案 > 无法在 Spring Boot 2 中上传 1gb 文件

问题描述

我正在尝试上传 1gb 的视频文件。但是服务器不允许上传它。

它返回以下错误:

15:46:02.164 [http-nio-8085-exec-10] ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/broadcast].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/broadcast] threw exception [Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3745) ~[?:?]
    at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:120) ~[?:?]
    at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:95) ~[?:?]
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:156) ~[?:?]
    at org.springframework.util.StreamUtils.copy(StreamUtils.java:143) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:110) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.util.FileCopyUtils.copyToByteArray(FileCopyUtils.java:162) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getBytes(StandardMultipartHttpServletRequest.java:245) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]

执行以下代码时出现此错误:

File file = new File(multipartFile.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(file);
fos.write(multipartFile.getBytes());
fos.close();

在java文件中。

下面是我的“SpringToolSuite4.ini”文件

-startup
plugins/org.eclipse.equinox.launcher_1.5.400.v20190515-0925.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.1000.v20190125-2016
-product
org.springframework.boot.ide.branding.sts4
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM

标签: javaspring-boot

解决方案


这里有两个问题

  1. 您看到的错误是因为您的 jvm 设置。检查您的内存设置。(-Xms 和 -Xmx)

  2. 默认情况下,你不能在 springboot 中上传这么大的文件。您需要增加默认限制 (10 MB)

在 Spring Boot 2.0 之前:

spring.http.multipart.max-file-size=-1
spring.http.multipart.max-request-size=-1

在 Spring Boot 2.0 之后:

spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1

-1 表示没有限制。强烈建议不要使用 -1 而是使用特定值。


推荐阅读