当前位置: 首页 > 知识库问答 >
问题:

jQuery Ajax文件上载:所需的MultipartFile参数“file”不存在

司徒元明
2023-03-14

背景

我正在Java8上构建一个Spring MVC web应用程序,并在Tomcat8上运行它。除了这些信息之外,Spring版本是4.1.6.releaseServlet3.1我给您介绍了环境背景,因为一些问题解决者提到该版本与此错误有关。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          
    <property name="maxUploadSize" value="20000000" />
</bean>
@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");
        }
    }

下面是我的表格

<form id="upload" method="POST" action="/uploadFile.json" enctype="multipart/form-data">
        File to upload: <input type="file" name="file" onchange="MyScript.uploadFile(this);"><br />
        <input type="submit" value="Upload"> Press here to upload the file!
    </form>

奇怪的事

是通过表单提交上传文件没有问题。它就像一个魅力!!对于表单提交我没有什么可抱怨的!!

            $.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);
                }
            });
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
<body><h1>HTTP Status 400 - Required MultipartFile parameter 'file' is not present</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>Required MultipartFile parameter 'file' is not present</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><hr class="line"><h3>Apache Tomcat/8.0.20</h3></body></html>

我已经用这个关键字搜索了谷歌,并尽可能多地搜索,就像我在发布关于stackoverflow的问题之前经常做的那样

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

共有1个答案

潘高岑
2023-03-14

这样试一试:

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);
                }
            });
 类似资料:
  • 简单示例:jsp中的表单 我的控制器的方法 我的上下文xml文件 描述由于被认为是客户端错误(例如,错误的请求语法、无效的请求消息帧或欺骗性的请求路由),服务器无法或不会处理请求。 Apache Tomcat/8.5.12

  • 这是我的控制器: 我的mvc-dispatcher-servlet.xml pom.xml:

  • 问题内容: 我正在尝试使用上传文件。下面是我的代码如何工作,但是如果我尝试使用它,则会得到以下信息: HTTP状态400-所需的MultipartFile参数’file’不存在 我不明白错误是什么。 我正在使用高级Rest Client进行测试,并且正在将文件作为附件上传。 我的Java代码: 问题答案: 春天需要 bean处理文件上载。 您应该在文件中注册该bean 。 Content-Type

  • 我试着这样做: ...然后像这样: 无关紧要。结果总是相同的“multipartrequest:Required MultipartFile参数'file'is not present”-服务器响应。 我会认为Spring在服务器上的工作不是很好,但是我在Swift(iOS)上做了等价的代码,它工作了!服务器在这里看到这个“文件”部分。 现在我希望它能在Android系统上安装。但是我甚至查看了修

  • 我正在尝试将图像作为广告中的字符串字段上传,但当将文件添加到正文时,我遇到了这个错误:“异常”:“org.springframework.web.multipart.support.MissingServletRequest estPartException”,“消息”:“所需的请求部分'file'不存在”。我在这里寻找有关此问题的答案,但没有任何帮助。我将很高兴得到任何帮助。 我的控制器: 我的