복붙노트

[SPRING] jQuery Ajax 파일 업로드 : 필수 MultipartFile 매개 변수 'file'이 (가) 없습니다.

SPRING

jQuery Ajax 파일 업로드 : 필수 MultipartFile 매개 변수 'file'이 (가) 없습니다.

배경

저는 Java8에서 Spring MVC 웹 애플리케이션을 만들고 tomcat8에서 실행하고 있습니다. 이 정보 외에도 Spring 버전은 4.1.6입니다. RELEASE 및 Servlet 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>

이상한 일

양식 제출을 통한 파일 업로드에는 문제가 없습니다. 그것은 매력처럼 작동합니다! 양식 제출에 불만을 제기 할 필요가 없습니다.

하지만이 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 Bad Request입니다.

나는이 키워드로 봤 거든 검색 할 수있는 한 많이, 내가 항상 stackoverflow에 대한 질문을 게시하기 전에 할

정말 왜 아약스가 여기에서 작동하지 않는지 모르겠다 !! 제출 업로드가 정상적으로 작동합니다.

해결법

  1. ==============================

    1.다음과 같이 시도해보십시오.

    다음과 같이 시도해보십시오.

    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);
                    }
                });
    
  2. from https://stackoverflow.com/questions/29488852/jquery-ajax-file-upload-required-multipartfile-parameter-file-is-not-present by cc-by-sa and MIT license