java 如何在tomcat servlet中限制上传的文件大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28564683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:50:29  来源:igfitidea点击:

how to limit uploaded filesize in tomcat servlet

javatomcatservlets

提问by somtomas

I need to set max filesize for uploaded files in my servlet running on tomcat. I tried multipart config which worked on jetty, but tomcat just ignored it. It means deployment on tomcat server caused even big files can be uploaded. My configuration:

我需要为在 tomcat 上运行的 servlet 中上传的文件设置最大文件大小。我尝试了在码头上工作的多部分配置,但 tomcat 只是忽略了它。这意味着部署在tomcat服务器上导致甚至可以上传大文件。我的配置:

<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>sk.test.MyServlet</servlet-class>
    <multipart-config>
        <max-file-size>1048576</max-file-size>
        <max-request-size>104857600</max-request-size>
    </multipart-config>
</servlet>

I already tried annotated configuration, which didnt work too.

我已经尝试过带注释的配置,但也不起作用。

Using: Tomcat 7.0.54, Servlet 3.0

使用:Tomcat 7.0.54,Servlet 3.0

I will appreciate any help, thanks

我将不胜感激任何帮助,谢谢

采纳答案by Do Nhu Vy

Set value of max file size, use annotation before servlet class or web.xmlconfig. See maxFileSizein annotation or <max-file-size></max-file-size>in xml config.

设置最大文件大小的值,在 servlet 类或web.xml配置之前使用注释。请参阅maxFileSize注释或<max-file-size></max-file-size>xml 配置。

@MultipartConfig(
    location="/tmp", 
    fileSizeThreshold=1024*1024,    // 1 MB
    maxFileSize=1024*1024*5,        // 5 MB 
    maxRequestSize=1024*1024*5*5    // 25 MB
)

or

或者

<multipart-config>
    <location>/tmp</location>
    <max-file-size>20848820</max-file-size>
    <max-request-size>418018841</max-request-size>
    <file-size-threshold>1048576</file-size-threshold>
</multipart-config>

Reference: https://docs.oracle.com/javaee/7/tutorial/servlets011.htm

参考:https: //docs.oracle.com/javaee/7/tutorial/servlets011.htm