上传文件时不存在所需的MultipartFile参数'file'

时间:2017-09-16 08:33:55

标签: java jquery spring-boot jboss

我正在尝试上传文件,但我收到Required MultipartFile parameter 'file' is not present 400 Bad Request org.springframework.web.bind.MissingServletRequestParameterException

我的代码在这里:

<form id="uploadrecords" method="post" enctype="multipart/form-data">                     
 <div class="col-md-12">
 <div class="form-group" style="margin-top: 11px !important;">
 <label for="uploadfile" class="col-md-4 control-label"><span class="mandatory"></span>File to upload:</label>
 <div class="col-md-6">
 <input type="file" class="filestyle" data-buttonName="btn-primary" name="file" id="upload" accept="*"/>
 </div>
 </div>
 <div class="form-actions" style="margin-top: 51px;margin-left: 358px;">
 <button type="submit"  class="btn btn-success" style="padding: 6px 12px;"   id="upload" ><i class="fa fa-cloud-upload"></i> Upload</button>
 <button type="button"  class="btn btn-danger"  style="padding: 6px 12px;" id="cancel"  ><i class="fa fa-ban"></i> Cancel</button> 
 </div>
 </div>
</form>

Jquery代码:

$("form#uploadrecords").submit(function(){                                  
    var formData = new FormData($(this)[0]);                                    
    $.ajax({
    url : '/uploadfile', 
    type: 'POST',
    data: formData,
    async: false,
    beforeSend: beforeSendHandler,
    success: function (data) {
    var msg=data.msg;
    var obj=data.obj;   
    if(obj != 0){
    $("#countfail").html(obj);
    $("#download-modal").modal('show');
    }else{
    bootbox.alert(msg);
    }
    },
    cache: false,
    contentType: false,
    processData: false
    });
});

Java代码:

@RequestMapping(value = "/uploadfile", headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
public @ResponseBody StatusResponse upload( @RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException, NoSuchFieldException, SecurityException, ParseException {
    StatusResponse sr = new StatusResponse();
    System.out.println("filename::::" + file.getOriginalFilename());
    //my logic here
    return sr;
}

它没有击中控制器类。我在Firebug console找到了错误。

我正在使用spring bootjboss-eap-6.4

我的代码有什么问题。如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果您正在使用@EnableAutoConfiguration,那么您需要执行以下所述的https://github.com/spring-projects/spring-boot/issues/2958

@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) 定义以下bean

@Bean(name =“multipartResolver”)public CommonsMultipartResolver commonsMultipartResolver(){CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(50 * 1024 * 1024);返回解析器; }

@Bean @Order(0)public MultipartFilter multipartFilter(){MultipartFilter multipartFilter = new MultipartFilter(); multipartFilter.setMultipartResolverBeanName( “multipartResolver”); return multipartFilter; }