使用 AngularJS 和 SpringMVC 进行多部分文件上传

     2023-02-26     67

关键词:

【中文标题】使用 AngularJS 和 SpringMVC 进行多部分文件上传【英文标题】:Multipart File Upload using AngularJS and SpringMVC 【发布时间】:2017-07-29 00:45:09 【问题描述】:

我是 angularJS 的新手,并尝试使用 angular JS 和 Spring MVC 上传文件,但无法获得所需的解决方案并最终在 JS Controller 中出现异常。

下面是代码,看看,请帮助我。谢谢

ApplicationContext.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000" /> <!-- setting maximum upload size -->
</bean>

JSP:

<div data-ng-controller='QuestionController'>
<form name="createChapForm" data-ng-submit="submitQue();" enctype="multipart/form-data" class="form-horizontal">
    <div class="form-group">
        <label class="control-label col-sm-3">Select Class * :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='class_id' data-ng-init='getClasses();' data-ng-change='getSubjectsClasswise(class_id);' class="form-control" required>
                    <option value="">--SELECT--</option>
                    <option data-ng-repeat='c in clss' value=" c.class_id"> c.class_name</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-3">Select Subject * :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='question.sid' data-ng-change='doGetChapters(question.sid);' class="form-control" required>
                    <option value="">--SELECT--</option>
                    <option data-ng-repeat='s in subsss' value=" s.sid"> s.subject_name</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-3">Select Chapter :</label>
        <div class="col-sm-8">
            <div class="col-sm-6">
                <select data-ng-model='question.chap_id' class="form-control" >
                    <option value="">ALL</option>
                    <option data-ng-repeat='c in chapters' value=" c.chap_id"> c.chap_name</option>
                </select>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="control-label col-sm-2" >Question :</div>
        <div class="col-sm-10 padding_0">
            <textarea data-ng-model='question.question_text' rows="5" class="form-control  " > </textarea>
            <div class="right">
                <div class="fileUpload btn btn-primary1 btn-sm">
                    <input type="file" data-ng-model="file" name="file" id="file"  id="q_id"  class="upload" />
                </div>
            </div>
        </div>
    </div>
</form>
</div>

AngularJS 控制器:

$scope.submitQue = function() 
    console.log('file is ' ); console.dir(file.files[0]);
    var URL =appURL+'/adm/doAddQuestion.do';
    var fd = new FormData();
    fd.append('file', file.files[0]);
    fd.append('questionBean', angular.toJson($scope.question, true));
    $http.post(URL, fd, 
        transformRequest : angular.identity,
        headers : 
            'Content-Type' : undefined
        
    ).success(function() 
        console.log('success');
    ).error(function() 
        console.log('error');
    );

Java 控制器:

@RequestMapping(value = "/doAddQuestion.do", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseBody String saveUserDataAndFile(@RequestParam(value = "file") MultipartFile file, @RequestBody QuestionBean questionBean) 
    System.out.println("output: "+questionBean.getQuestion_text());
    // Im Still wotking on it
    return "";

例外情况:

Mar 08, 2017 7:46:46 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
WARNING: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]
Mar 08, 2017 7:46:46 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver logException
WARNING: Handler execution resulted in exception: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
 at [Source: java.io.PushbackInputStream@bc03e1; line: 1, column: 3]

【问题讨论】:

你的错误很明显 Expected MultipartHttpServletRequest: is a MultipartResolver configured? @see Multipart Resolver @EddieB 已更改,但仍然给出相同的异常 '改变'?你需要configure a multipart resolver...@更多信息Configure Multipart Resolver @EddieB 更新了改动,请看一下 您的原始问题。 multipart resolver 已解决。您需要遵循 SO 规则并为 new problem 发布新问题 【参考方案1】:

在你添加angular.js文件的地方添加这些.js文件angular-file-upload.js,angular-file-upload-shim.js,ng-file-upload.js,ng-file-upload-shim.js

您可以从此链接Angular File For Upload.下载

然后在angular.module 中添加ngFileUpload,'angularFileUpload',见下一行。

angular.module('formSubmit', [ 'ngFileUpload',
            'angularFileUpload',  'ui.router' ]);

然后像这样在你的角度控制器中添加$upload

app.controller('FormSubmitController', function($scope, $http, $upload)

在您的 Angular 代码中使用 $upload.upload 而不是 $http.post

$upload.upload(
    url : 'doAddQuestion.do',
    file : yourFile,
    data : $scope.questionBean,
    method : 'POST'
);

更换你的弹簧控制器。

@RequestMapping(value = "/doAddQuestion.do", method = RequestMethod.POST, headers = ("content-type=multipart/*"))
public @ResponseBody String saveUserDataAndFile(@RequestParam("file") MultipartFile file, QuestionBean questionBean) 
    System.out.println("output: "+questionBean.getQuestion_text());
            // Im Still wotking on it
    return "";

【讨论】:

这是什么yourFile 在你的情况下,你必须用这个代码替换file.files[0] 在控制台显示错误Error: [$injector:unpr] Unknown provider: $uploadProvider &lt;- $upload 我已经编辑了我的答案,请按照所有步骤操作。 我使用了确切的文件和建议的控制器参数列表。我收到了400 (Bad Request) 有什么建议吗?【参考方案2】:

使用以下代码更新您的请求映射:

 @RequestMapping(value = "/upload-file", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

它将删除您的多部分异常。

【讨论】:

已更改但仍给出相同的异常 我认为您的多部分异常现在已解决,当前问题可能在您的请求对象中。 no.. 现在它给出了一些不同的例外.. 我更新了问题,看看 “QuestionBean”是你的实体类吗?如果是,则实现 Serializable,如以下链接所示:***.com/questions/34888326/…。让我知道它是否适合你 @hrdkisback - 我正在尝试与您在回答中提到的完全相同的功能..即使我面临错误。它在控制台中显示错误 Error: [$injector:unpr] Unknown provider: $uploadProvider

angularjs和springmvc的ajaxget错误

我有一个角度函数,它使用带有GET和params的$http请求:$scope.getMatchingRecipe=function(){$http({method:"GET",url:"/recipemanagement/getMatchingRecipeList",params:{matchingText:$scope.matchingRecipe.text}}).success(functi 查看详情

Spring MVC 和 Angularjs

】SpringMVC和Angularjs【英文标题】:SpringMVCandAngularjs【发布时间】:2013-05-1302:44:11【问题描述】:目前我正在尝试学习AngularJS,但首先我想使用Springmvc设置我的环境。目前我只想休息工作,但我怀疑将资源放在SpringMVC中的最佳方式... 查看详情

如何使用 Spring Security 和 Angularjs 保护 Spring Rest 服务?

】如何使用SpringSecurity和Angularjs保护SpringRest服务?【英文标题】:HowtoSecureSpringRestServiceswithSpringSercurityandAngularjs?【发布时间】:2014-04-1322:19:28【问题描述】:我有一个带有Rest-Services和AngularJSWebFrontend的SpringMVC服务器后端。我想... 查看详情

使用 AngularJS 配置 Spring MVC

】使用AngularJS配置SpringMVC【英文标题】:ConfigureSpringMVCwithAngularJS【发布时间】:2012-12-1605:39:12【问题描述】:我希望能够在客户端使用SpringMVC作为REST服务器和AngularJS。我有几个REST网址:/休息/产品/rest/products/id我有几个用户界... 查看详情

AngularJS/Spring MVC,HttpSession 不持久

】AngularJS/SpringMVC,HttpSession不持久【英文标题】:AngularJS/SpringMVC,HttpSessionnotpersistent【发布时间】:2016-09-3012:50:24【问题描述】:我们正在开发一个网络应用程序,我们正在使用SpringMVC(以及SpringBoot和SpringSecurity)和AngularJS。因... 查看详情

AngularJS 和 Spring MVC 安全性

】AngularJS和SpringMVC安全性【英文标题】:AngularJSandSpringMVCsecurity【发布时间】:2015-03-0513:25:48【问题描述】:我有一个用AngularJS编写的前端和一个SpringMVC后端。我的想法是只保护RESTAPI服务,并在进行未经授权的服务调用时使用Ang... 查看详情

使用 Spring MVC 和 AngularJS 的方法 DELETE

】使用SpringMVC和AngularJS的方法DELETE【英文标题】:MethodDELETEwithSpringMVCandAngularJS【发布时间】:2015-05-0812:04:36【问题描述】:我的RESTfull服务有问题,应该从数据库中删除记录。当我使用REST请求以角度调用函数时,我收到FireBug错... 查看详情

使用 AngularJS 和 Spring Security 的单页应用程序中需要 AntMatchers

】使用AngularJS和SpringSecurity的单页应用程序中需要AntMatchers【英文标题】:AntMatchersneededinaSinglePageApplicationusingAngularJSandSpringSecurity【发布时间】:2016-09-0122:01:38【问题描述】:我有一个单页应用程序客户端使用AngularJS,而服务器... 查看详情

angularjs——ngresourcerestfulapis使用

...持久化新的数据对象更新存在的数据对象代码片段包含了AngularJs代码和SpringMVC代码,以能够让你简单快速的上手。想要$resource服务工作,需要添加一段实际代码:应用angular-resource.js文件,你可以使用GoogleHostedLibraries来实现。<s... 查看详情

使用 laravel 保护 javascript 资源

...1:05【问题描述】:我已经用laravel5.2构建了restapi,将它与angularJS集成并用jwt保护它。这是我第一次使用jwt,而不是angularjs,在我过去的项目中(使用springmvc/security、angularJS和session而 查看详情

哪个弹簧视图解析器与 angularjs 配合得很好?

】哪个弹簧视图解析器与angularjs配合得很好?【英文标题】:Whichspringviewresolverplaysnicewithangularjs?【发布时间】:2014-09-1008:50:49【问题描述】:我正在编写一个使用angularjs和springmvc作为REST服务提供者和部分视图提供者的web应用程... 查看详情

Spring CSRF + AngularJs

】SpringCSRF+AngularJs【英文标题】:【发布时间】:2015-10-0201:22:00【问题描述】:我已经尝试了很多关于这个主题的回答,没有人适合我。我有一个基本的CRUD和SpringMVC4.1.7,SpringSecurity3.2.3在MySQL+Tomcat7上工作。问题是,当我尝试使... 查看详情

如何提高 Spring MVC - Hibernate - JSP - AngularJS v1.6 的性能? [关闭]

】如何提高SpringMVC-Hibernate-JSP-AngularJSv1.6的性能?[关闭]【英文标题】:HowtoincreaseperformanceinSpringMVC-Hibernate-JSP-AngularJSv1.6?[closed]【发布时间】:2018-05-0603:45:48【问题描述】:给我一​​些想法/建议/解决方案,以更快地检索数据和... 查看详情

为啥我在 AngularJs 帖子中收到 400 个错误请求?

】为啥我在AngularJs帖子中收到400个错误请求?【英文标题】:WhyamIgetting400badrequestwithAngularJspost?为什么我在AngularJs帖子中收到400个错误请求?【发布时间】:2014-12-0602:43:51【问题描述】:我使用SpringMVC和AngularJs来创建一个Web应用... 查看详情

使用 AngularJS 和 MeteorJS

】使用AngularJS和MeteorJS【英文标题】:UsingAngularJSwithMeteorJS【发布时间】:2012-10-2011:47:00【问题描述】:所以我对这两种技术都很陌生。我的计划是使用MeteorJS实现他们使用Backbone(https://github.com/philipkobernik/backbone-tunes)制作的Peepcode... 查看详情

如何在骨干和angularjs中使用reactJS组件

】如何在骨干和angularjs中使用reactJS组件【英文标题】:howtousereactJScomponentinsidebackboneandangularjs【发布时间】:2016-08-0320:23:23【问题描述】:我有骨干应用程序和angularJS应用程序,同时,我正在使用reactJS创建组件库。现在的目标... 查看详情

AngularJS:未发送 X-Auth-Token(错误 401)

】AngularJS:未发送X-Auth-Token(错误401)【英文标题】:AngularJS:X-Auth-Tokennotsent(error401)【发布时间】:2014-09-0822:17:30【问题描述】:我在这里是因为我尝试了所有方法,但我不明白我做错了什么。作为后端,我使用SpringMVC、Rest和Sp... 查看详情

springmvc的使用和mybatis介绍

本周主要学习了SpringMVC的使用和mybatis介绍SpringMVC概念:1.SpringWebMVC是一种基于Java的实现了WebMVC设计模式的请求驱动类型的轻量级Web框架2.使用了MVC架构模式的思想,将web层进行职责解耦3.基于请求驱动指的就是使用请求-响应模型... 查看详情