java spring上传文件问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16037747/
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-10-31 21:42:36  来源:igfitidea点击:

Spring upload file problems

javaspringmodel-view-controllermultipart

提问by user2160696

I need to upload file from browser to server. I use spring 3.2 as my web framework.

我需要将文件从浏览器上传到服务器。我使用 spring 3.2 作为我的网络框架。

So i configured my app like this.

所以我这样配置我的应用程序。

1 - I got web.xml

1 - 我得到了 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>racoonsoft.chaos.settings</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>admin/library</welcome-file>
    </welcome-file-list>

</web-app>

2 - MainConfig class

2 - MainConfig 类

@Configuration
@Import({WebConfig.class })
public class MainConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public static ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }

    @Bean
    public static StandardServletMultipartResolver multipartResolver() {
        StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
        return resolver;
    }
}

3 - Controller to handle multipart uploads

3 - 处理分段上传的控制器

@Controller
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
        maxFileSize=1024*1024*10,      // 10MB
        maxRequestSize=1024*1024*50)
public class FileUpload
{
    public static final int UPLOAD_RESULT_OK = 100000;
    @Autowired
    BookDao book_dao;

    @RequestMapping(value = "/admin/library/upload_file", method = RequestMethod.POST)
    public String saveFiles(@RequestParam("file-file") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            byte[] bytes = file.getBytes();
            return "redirect:caps/total_fail";
        }
        else
        {
            return "redirect:caps/total_fail";
        }
    }
}

4 - jsp where i placed my form to submit files

4 - 我在其中放置表单以提交文件的 jsp

...<form method="post" action="/admin/library/upload_file" enctype="multipart/form-data">
                <input type="text" name="name"/>
                <input type="file" name="file-file"/>
                <input type="submit"/>
            </form>...

When i submit my form i got an Exception

当我提交表单时出现异常

org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file-file' is not present
    org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:202)

I got no idea why. When i remove @RequestParam annotaion i got my method invoked but file parameter = null. What is my problem?

我不知道为什么。当我删除@RequestParam annotaion 时,我调用了我的方法,但文件参数 = null。我的问题是什么?

采纳答案by user64141

I fixed this problem by adding the following to my spring config file:

我通过将以下内容添加到我的 spring 配置文件中解决了这个问题:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

(The error I was getting was "org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'myFile' is not present

(我得到的错误是“org.springframework.web.bind.MissingServletRequestParameterException:Required MultipartFile parameter 'myFile' is not present

回答by z0mb1ek

i can do it with

我可以做到

@Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {

        MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/",100000, 200000, 50000);

        registration.setMultipartConfig(multipartConfigElement);

    }

回答by realgt

@user64141 is right but if using Java config instead of xml, try

@user64141 是对的,但如果使用 Java 配置而不是 xml,请尝试

@Bean
public MultipartResolver multipartResolver() {
    return new CommonsMultipartResolver();
}

回答by mthmulders

You also need the MultipartFilterconfigured for your webapp. According to its Javadoc, it resolves multipart requests using the MultipartResolver (but you have that one configured already). You'll need to map it to (part of) the request path for Controller that handles the file uploads.

您还需要MultipartFilter为您的 webapp 配置。根据其 Javadoc,它使用 MultipartResolver 解析多部分请求(但您已经配置了该请求)。您需要将其映射到处理文件上传的 Controller 的(部分)请求路径。

First, add the MultipartFilterto your web.xml:

首先,添加MultipartFilter到您的 web.xml:

<filter>
    <filter-name>multipartFilter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>

Next, map the filter to (a part of) the URL that needs to accept file uploads:

接下来,将过滤器映射到(一部分)需要接受文件上传的 URL:

<filter-mapping>
    <filter-name>multipartFilter</filter-name>
    <url-pattern>/admin/library/upload_file</url-pattern>
</filter-mapping>