복붙노트

[SPRING] Angularjs 파일 업로드가 작동하지 않습니다.

SPRING

Angularjs 파일 업로드가 작동하지 않습니다.

자바 컨트롤러 클래스 :

@RequestMapping(value = "/upload" , method = RequestMethod.POST , consumes="multipart/form-data")
public void upload(@RequestParam MultipartFile file1) {
        System.out.println("*****"+ file1);
  }

html 파일 :

<input id="file-0a" class="file" type="file" file-model="myFile"/>
     <button ng-click="uploadFile()">upload me</button>

각도 js :

$scope.uploadFile = function(){
          var file = $scope.myFile;
          console.log('file is ' + JSON.stringify(file));
          var fd = new FormData();
          fd.append('file', file);
          var resource = /upload;    
            $http.post(resource, fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function(){ }).error(function(){ }); 
         }

그리고 이것은 서버 로그에서 이해할 수없는 오류입니다.

INFO: Server startup in 38138 ms
Feb 14, 2015 11:45:17 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet dispatcher threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:348)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
    at org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler.handleRequest(DefaultServletHttpRequestHandler.java:122)
    at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:467)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:434)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:205)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Feb 14, 2015 11:45:17 PM org.apache.catalina.core.StandardHostValve custom
SEVERE: Exception Processing ErrorPage[errorCode=0, location=/error.html]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Cannot forward after response has been committed
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)

해결법

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

    1.다음을 시도하십시오. 그것은 나를 위해 잘 작동합니다.

    다음을 시도하십시오. 그것은 나를 위해 잘 작동합니다.

    HTML 당신은

    <input id="file-0a" class="file" type="file" file-model="myFile" name="myFile" />
         <button ng-click="uploadFile()">upload me</button>
    

    입력 이름을 기록하십시오.

    그런 다음 JS 컨트롤러 메소드에서

    $scope.uploadFile = function(){
        var formData=new FormData();
        formData.append("file",myFile.files[0]); //myFile.files[0] will take the file and append in formData since the name is myFile.
        $http({
            method: 'POST',
            url: '/upload', // The URL to Post.
            headers: {'Content-Type': undefined}, // Set the Content-Type to undefined always.
            data: formData,
            transformRequest: function(data, headersGetterFunction) {
                return data;
            }
        }).success(function(data, status) {  
        })
        .error(function(data, status) {
        });
    }
    

    이제 Java Controller 클래스에서

    @RequestMapping(value = "/upload" , method = RequestMethod.POST)
    public void upload(HttpServletRequest request) {
    
        //org.springframework.web.multipart.MultipartHttpServletRequest
        MultipartHttpServletRequest mRequest;
        mRequest = (MultipartHttpServletRequest) request;
    
        Iterator<String> itr = mRequest.getFileNames();
        while (itr.hasNext()) {
            //org.springframework.web.multipart.MultipartFile
            MultipartFile mFile = mRequest.getFile(itr.next());
            String fileName = mFile.getOriginalFilename();
            System.out.println("*****"+ fileName);
    
            //To copy the file to a specific location in machine.
            File file = new File('path/to/new/location');
            FileCopyUtils.copy(mFile.getBytes(), file); //This will copy the file to the specific location.
        }
    }
    

    희망이 당신을 위해 작동합니다. 예외 처리도 수행하십시오.

  2. from https://stackoverflow.com/questions/28523453/angularjs-file-upload-not-working by cc-by-sa and MIT license