jQuery Ajax文件上传:所需的MultipartFile参数'file'不存在 [英] jQuery Ajax file upload : Required MultipartFile parameter 'file' is not present

查看:71
本文介绍了jQuery Ajax文件上传:所需的MultipartFile参数'file'不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我正在Java8上构建Spring MVC Web应用程序,并在tomcat8上运行它.除了此信息之外,Spring版本是4.1.6.RELEASEServlet 3.1我为您提供了环境背景,因为一些解决问题的人提到该版本与此错误有关.

我的密码

下面是root-context.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          
    <property name="maxUploadSize" value="20000000" />
</bean>

下面是我的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");
        }
    }

下面是我的表格

<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>

陌生事物

是通过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

浏览器说类似...

<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>

问题是不存在必需的MultipartFile参数'file' 400错误的请求.

我一直在用这个关键字搜索并尽可能多地进行搜索,就像在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);
                }
            });

BACKGROUND

I'm building a Spring MVC web application on Java8 and running it on tomcat8. In addition to this info, Spring version is 4.1.6.RELEASE and Servlet 3.1 I'm giving you the environmental background, because some problem solvers mentioned the version is related to this error.

MY CODE

Below is the root-context.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          
    <property name="maxUploadSize" value="20000000" />
</bean>

Below is my 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");
        }
    }

Below is my form

<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>

STRANGE THING

is that uploading files through form submit has no problem. It works like a charm !! I have nothing to complain for form submit !!

BUT THIS AJAX BELOW DOESN'T WORK

            $.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);
                }
            });

When I'm trying to upload file with above ajax call, server throws me this error.

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

And browser says something like...

<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>

The point is Required MultipartFile parameter 'file' is not present and 400 Bad Request.

I've googled with this keyword and searched as much as I could, like I always do before posting a question on stackoverflow

I really don't get it why only ajax doesn't work here!! when submit upload works just fine.

解决方案

Give a try like this:

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);
                }
            });

这篇关于jQuery Ajax文件上传:所需的MultipartFile参数'file'不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆