Spring - AngularJS - 文件上传 - org.apache.commons.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界

时间:2017-08-17 20:04:04

标签: java angularjs spring spring-mvc file-upload

在将文件从angular上传到我的Java Spring MVC Web应用程序服务器时,我面临以下异常

<form role="form" name="attachForm" class="form-horizontal" >
        <div class="form-group">
                <input class="col-xs-12" id="uploadFile" type="file" name="uploadFile" file-model ="myFile" ng-disable="closeHidden" required />
            </div>
        </div>
</form>

在我的AngularJs中

var saveFileURL = "caseapi/saveFile";
var fd = new FormData();
fd.append('file', scope.myFile);
return $http.post(saveFileURL,fd,{
                transformRequest: angular.identity,
                headers: {
                            "Content-Type": undefined
                        }
                });

我的指示

(function() {
define([ 'appModule'], function(app) {
app.directive('fileModel', [ '$parse', function($parse) {
    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            console.log("fileModelDir");
            element.bind('change', function() {

                scope.$apply(function() {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
} ]);
});
}).call(this);

服务器侧

@RequestMapping(value = "/saveFile", method = RequestMethod.POST)
public void saveFile( MultipartFile fd, HttpServletRequest request, HttpServletResponse response) throws Exception {
    logger.info("SAVE FILE fd : " +fd);
    logger.info("File name :" + fd.getName());
    try 
    {
        /** TODO: Implement file handling **/
        logger.info("saveDraft serviceResponse: ");
        handleResponse(response, serviceResponse);

        logger.info("Exitting saveDraft");
    } catch (Exception ex) {
        logger.error("Error while calling service: ",ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

以下是错误

SEVERE: Servlet.service() for servlet [GVEClientExperience] in context 
with path [] threw exception [Request processing failed; nested 
exception is org.springframework.web.multipart.MultipartException: 
Could not parse multipart servlet request; nested exception is 
org.apache.commons.fileupload.FileUploadException: the request was 
rejected because no multipart boundary was found] with root cause
org.apache.commons.fileupload.FileUploadException: the request was 
rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.
<init>(FileUploadBase.java:990)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:139)
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1041)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:887)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.ebaysf.web.cors.CORSFilter.handleSimpleCORS(CORSFilter.java:303)
at org.ebaysf.web.cors.CORSFilter.doFilter(CORSFilter.java:161)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:615)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1729)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

我已经提到了这篇文章Spring MVC - AngularJS - File Upload - org.apache.commons.fileupload.FileUploadException 但它没有帮助。我是Angular的新手。想了解这里有什么不对吗?

6 个答案:

答案 0 :(得分:1)

将enctype属性添加到FORM标记。

<form enctype="multipart/form-data">

答案 1 :(得分:1)

迟到但可以帮助某人:

使用ngFileUpload,如下所示:

$scope.uploadFile = function (file, param1, param2)
{
    var params ={'param1': param1, 'param2': param2};

    Upload.upload({
        url: 'http://localhost/uploadFile',
        data: {file:file},
        params: params
    }).then(function (resp) {
        console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
    }, function (resp) {
        console.log('Error status: ' + resp.status);
    }, function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    }).catch (function onError(data){
        console.error("Upload pic exception");
        console.error(JSON.stringify(data));
 });;        
};

您也可以将参数放在数据变量中。

答案 2 :(得分:0)

您需要在控制器中指定要使用的数据类型,并使用文件的密钥添加请求参数

@RequestMapping(value = "/saveFile", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public void saveFile(@RequestParam(name="fd") MultipartFile fd, HttpServletRequest request, HttpServletResponse response) throws Exception {

并且不需要contentType:undefined

 return $http.post(saveFileURL,fd,{
            transformRequest: angular.identity,

            });

并在表单中添加加密类型ad daddygames提到

 enctype="multipart/form-data">

答案 3 :(得分:0)

您的请求似乎有问题。试着这样做。

return $http.post(saveFileURL,fd,{
            transformRequest: angular.identity,
            headers: {
                        "Content-Type": "multipart/form"
                    }
            });

这是提到它的W3C规范

  

其中一个或多个不同的数据集合在一个主体中,“multipart”Content-Type字段必须出现在实体的标题中。

https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html

答案 4 :(得分:0)

我们已经设法使用简单而强大的第三方指令angular-upload来处理这样的要求。使用非常简单明了。您可以在文档中找到更多详细信息。

在HTML页面中:

<div
 class="btn btn-primary btn-upload"
 upload-button
 url="/upload"
 on-success="onSuccess(response)">Upload</div>

在角度控制器中:

$scope.onSuccess = function(response) {
    // Do something
};

在Spring Controller中:

@RequestMapping(value = "upload", method = RequestMethod.POST)
public void uploadAccessFile(@RequestParam("file") MultipartFile file) {
    // Do something with file
}

最后在你的配置中:

@Bean
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("utf-8");
    return resolver;
}

答案 5 :(得分:0)

添加“Content-Type”:在请求和数据类型中未定义以消耗= {“multipart / form-data”})