Angularjs文件上传不工作

Angularjs文件上传不工作

本文介绍了Angularjs文件上传不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的控制器类:

  @RequestMapping(值=/上传,方法= RequestMethod.POST,消耗=的multipart / form-data的)
公共无效上传(@RequestParam MultipartFile文件1){
        的System.out.println(*****+ file1的);
  }

HTML文件:

 <输入ID =文件0A级=文件类型=文件文件模式=MYFILE/>
     <按钮NG点击=一个UploadFile()>上传ME< /按钮>

角JS:

  $ scope.uploadFile =功能(){
          var文件= $ scope.myFile;
          的console.log('文件是+ JSON.stringify(文件));
          变种FD =新FORMDATA();
          fd.append(文件,文件);
          VAR资源= /上传;
            $ http.post(资源,FD {
                transformRequest:angular.identity,
                标题:{'内容类型':未定义}
            })成功(函数(){})错误(函数(){});
         }

这是我不服务器日志理解的错误:

 信息:在38138毫秒Server启动
2015年2月14日下午11时45分十七秒org.apache.catalina.core.ApplicationDispatcher调用
重度:Servlet.service()进行servlet调度抛出异常
java.lang.IllegalStateException:不能向前后反应一直致力于
    在org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:348)
    在org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
    在org.springframework.web.servlet.resource.DefaultServletHtt$p$pquestHandler.handleRequest(DefaultServletHtt$p$pquestHandler.java:122)
    在org.springframework.web.servlet.mvc.Htt$p$pquestHandlerAdapter.handle(Htt$p$pquestHandlerAdapter.java:51)
    在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    在javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    在javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    在org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
    在org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
    在org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
    在org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:467)
    在org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
    在org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:434)
    在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:205)
    在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    在org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    在org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    在org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:611)
    在org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:316)
    在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:615)
    在org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)
    在java.lang.Thread.run(Thread.java:745)2015年2月14日下午11时45分十七秒org.apache.catalina.core.StandardHostValve定制
重度:异常处理的errorPage [错误code = 0,位置= /的error.html]
org.springframework.web.util.NestedServletException:请求处理失败;嵌套的例外是java.lang.IllegalStateException:无法回应一直致力于向前后
    在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    在javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)


解决方案

请尝试以下方法。这是工作对我罚款。

HTML你应该有

 <输入ID =文件0A级=文件类型=文件文件模式=MYFILENAME =MYFILE/>
     <按钮NG点击=一个UploadFile()>上传ME< /按钮>

请注意输入的名称。

然后在JS控制器方法,你应该有

  $ scope.uploadFile =功能(){
    VAR FORMDATA =新FORMDATA();
    formData.append(文件,myFile.files [0]); //myFile.files[0]将采取文件,并在追加FORMDATA因为名字是MyFile的。
    $ HTTP({
        方法:POST,
        网址:'/上传',//的URL来邮。
        标题:{'内容类型':未定义} //内容类型总是被设置为未定义。
        数据:FORMDATA,
        transformRequest:功能(数据,headersGetterFunction){
            返回的数据;
        }
    })。成功(功能(数据,状态){
    })
    .error(功能(数据,状态){
    });
}

现在在Java Controller类

  @RequestMapping(值=/上传,方法= RequestMethod.POST)
公共无效上传(HttpServletRequest的请求){    //org.springframework.web.multipart.MultipartHttpServletRequest
    MultipartHttpServletRequest mRequest;
    mRequest =(MultipartHttpServletRequest)请求;    迭代器<串GT; ITR = mRequest.getFileNames();
    而(itr.hasNext()){
        //org.springframework.web.multipart.MultipartFile
        MultipartFile MFILE = mRequest.getFile(itr.next());
        字符串文件名= mFile.getOriginalFilename();
        的System.out.println(*****+文件名);        //将文件复制到机器的特定位置。
        档案文件=新的文件(路径/要/新/位置');
        FileCopyUtils.copy(mFile.getBytes(),文件); //这将文件复制到特定位置。
    }
}

希望这会为你工作。而这样做的异常处理也。

Java Controller class:

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

html file:

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

And this is the error I dont understand in the server log:

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)
解决方案

Try the following. It is working fine for me.

HTML You should have

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

Note the name of the input.

Then in JS controller method you should have

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

Now in Your Java Controller class

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

Hope this works for You. And do Exception Handling also.

这篇关于Angularjs文件上传不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:31