Angularjs文件上传无法正常工作

时间:2015-02-15 05:58:16

标签: java angularjs spring

Java Controller类:

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

angular 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 个答案:

答案 0 :(得分: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.
    }
}

希望这对你有用。并且还要进行异常处理。