表单类型为"文件"由于" MultipartException,因此未提交给服务器:当前请求不是多部分请求"

时间:2014-12-15 21:52:06

标签: spring spring-mvc spring-boot multipartform-data

在我目前的spring-boot项目中,我在我的主Application类中为MultipartFile配置了这个配置:

  @Bean
  MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("128KB");
    factory.setMaxRequestSize("128KB");
    return factory.createMultipartConfig();
  }

我的表单有这种格式:

<form role="form" class="form" action="/Categoria/cadastra" method="post" enctype="multipart/form-data">
...
</form>

在我的控制器中,此请求的处理程序是这个方法:

  @RequestMapping(value = "cadastra", method=RequestMethod.POST)
  @ResponseBody
  public void cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="icone", required=false) MultipartFile icone, @RequestParam(value="fotos", required=false) MultipartFile fotos[]) {
    ...
  }

但是当我尝试从表单提交数据时,我收到此错误:

MultipartException: The current request is not a multipart request
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.assertIsMultipartRequest(RequestParamMethodArgumentResolver.java:216)
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:167)
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:89)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

任何人都可以告诉我如何解决这个问题?

更新

我尝试过另一种方式:

Application.java:

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {
  public static void main(String[] args) throws Throwable {
    SpringApplication.run(Application.class, args);
  }
}

application.properties:

# Multipart configuration
multipart.fileSizeThreshold = 131072
multipart.location = ${user.home}/.mystore/uploads
multipart.maxFileSize = -1
multipart.maxRequestSize = -1

这不起作用。任何人都有一个有用的暗示这个代码有什么问题吗?

更新2

如果这有任何问题,我不会这样做,但是当我检查浏览器的网络控制台工具时,我注意到input[type=file]字段都没有作为请求的参数列出,尽管它们都是应该存在(所有都有一个属性name)。

更新3

我尝试使用外部lib,jquery.form解决此问题,将我的代码更改为:

$("form.form").ajaxForm(function(data){
    if(data == "") {
        $("#yes").show();
    } else {
        var $temp  = $('<div/>', {html:data});
        $("#not").find(".text").empty();
        $("#not").find(".text").html( $temp.remove('head').html() );
        $("#not").show();
    }
});

它有效,但现在我正在寻找一个不需要在我的项目中添加额外的jquery lib的解决方案。

2 个答案:

答案 0 :(得分:6)

我猜application.properties配置存在问题。您已将maxFileSizemaxRequestSize设置为-1。我不确定这是否正确。

阅读this guide page以了解如何在Spring启动应用程序中完成文件上传。

<强>更新 如果您的表单包含要提交给服务器端的file内容和textfields,则应创建一个域类,其属性名称与表单元素相同。并将完整表单提交到服务器端,获取@ModelAttribute中的所有表单数据。现在ModelAttribute也将包含文件和文本字段。示例代码供您参考:

以下是携带表单数据的DTO类:

public class PartDetailsDto {
    private String PartId;
    private MultipartFile productImage;
    private MultipartFile approvalLetter;
}

以下是Controller方法:

@RequestMapping(value = "parts/create", method = RequestMethod.POST)
public String createPart(@ModelAttribute("partInfo") PartDetailsDto partDetails) {
    // Here in partDetails you will get form data
}

JSP表单将是这样的:

<form autocomplete="off" action="${pageContext.request.contextPath}/parts/create" method="POST" name="partInfo" enctype="multipart/form-data">
    // here you will have text fields and file content
</form>

答案 1 :(得分:4)

在多部分客户端使用JQuery文件上传,在服务器端添加此代码就像魅力一样。

   /**
 * File upload by JQuery Upload file
 *
 * @param defaultMultipartHttpServletRequest
 *
 * @param id
 * @return
 */
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
@ResponseBody
public Map uploadFiles(MultipartHttpServletRequest defaultMultipartHttpServletRequest,

您是否在服务器端尝试过MultipartHttpServletRequest?。

在客户端,JQuery文件上传看起来像。

function initializeFileUpload() {
$("#fileuploader").uploadFile({
    url: 'url',
    dragDrop: true,
    multiple: true,
    autoSubmit: true,
    showStatusAfterSuccess: false,
    showAbort: false,
    showDone: false,
    maxFileSize: MAX_UPLOAD_SIZE,
    fileName: 'fileData',
    uploadButtonClass: 'btn btn-primary col-xs-3',
    onSuccess: function (files, data, xhr) {
    showStatus(callbackAction.ERROR);

    }
});