jQuery Ajax文件上传:不存在所需的MultipartFile参数’file’

背景

我正在Java8上构建一个Spring MVC Web应用程序并在tomcat8上运行它。 除了这个信息,Spring版本是4.1.6.RELEASEServlet 3.1我给你的环境背景,因为一些问题解决者提到版本与这个错误有关。

我的代码

下面是root-context.xml

    

下面是我的FileController

 @Controller public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); private static final String UploadFolder = "Files"; @RequestMapping("/uploadFile") @ResponseBody public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException { String fileName = ""; PrintWriter script = response.getWriter(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); fileName = FilenameUtils.getName(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(fileName); String base = System.getProperty("catalina.home"); File dir = new File(base + File.separator + UploadFolder); if (!dir.exists()) { dir.mkdirs(); } Date date = new Date(); String year = DateTimeUtility.getInstance().getYear(date); String month = DateTimeUtility.getInstance().getMonth(date); String uniqueFileName = DateTimeUtility.getInstance().getDateTime(date); File dateDir = new File(base + File.separator + UploadFolder + File.separator + year + File.separator + month); if (!dateDir.exists()) { dateDir.mkdirs(); } File uploadedFile = new File(dateDir.getAbsolutePath() + File.separator + uniqueFileName + WordCollections.UNDERBAR + fileName); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadedFile)); stream.write(bytes); stream.close(); logger.info("Server File Location = " + uploadedFile.getAbsolutePath()); script.write("Uploading file was successful"); } catch (Exception e) { logger.error("Server failed to upload this file : " + fileName); script.write("Uploading file was failed"); } } else { logger.error("The requested file is empty"); script.write("Uploading file was empty"); } } 

以下是我的表格

 
File to upload:
Press here to upload the file!

奇怪的事情

是通过form submit上传文件没有问题。 它就像一个魅力! form submit我没有什么可抱怨的!

但是这下面的AJAX不起作用

  $.ajax({ type: "POST", url: "/uploadFile", data: {name: "file", file: inputElement.files[0]}, contentType: 'multipart/form-data;boundary=----WebKitFormBoundary0XBBar2mAFEE8zbv', processData: false, cache: false, /*beforeSend: function(xhr, settings) { xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p"); settings.data = {name: "file", file: inputElement.files[0]}; },*/ success: function (result) { if ( result.reseponseInfo == "SUCCESS" ) { } else { } }, error: function (result) { console.log(result.responseText); } }); 

当我尝试使用上面的ajax调用上传文件时,服务器会抛出此错误。

 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/uploadFile] 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /uploadFile 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException] 2015-04-07 18:37:30 DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'fileController' 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public void com.company.web.controller.FileController.uploadFile(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletResponse) throws java.io.IOException]: org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling 2015-04-07 18:37:30 DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request 

浏览器说像……

 

HTTP Status 400 - Required MultipartFile parameter 'file' is not present

type Status report

message Required MultipartFile parameter 'file' is not present

description The request sent by the client was syntactically incorrect.


Apache Tomcat/8.0.20

要点是必需的MultipartFile参数’file’不存在400 Bad Request

我用Google搜索了这个关键字并尽可能多地搜索,就像我在stackoverflow上发布问题之前一样

我真的不明白为什么只有ajax在这里不起作用!! 当提交上传工作正常。

尝试这样:

 var fd = new FormData(); fd.append( "file", $("input[name=file]").files[0]); $.ajax({ type: "POST", url: "/uploadFile", data: fd, contentType: false, processData: false, cache: false, /*beforeSend: function(xhr, settings) { xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p"); settings.data = {name: "file", file: inputElement.files[0]}; },*/ success: function (result) { if ( result.reseponseInfo == "SUCCESS" ) { } else { } }, error: function (result) { console.log(result.responseText); } });