angular2 formdatapost请求参数怎么放在formdata

解决angular的$http.post()提交数据时后台接收不到参数值问题的方法_AngularJS-js教程-PHP中文网QQ群微信公众号还没有收藏解决angular的$http.post()提交数据时后台接收不到参数值问题的方法_AngularJS写此文的背景:在学习使用angular的$http.post()提交数据时,后台接收不到参数值,于是查阅了相关资料,寻找解决办法。写此文的目的:通过上面提到的文章中的解决之道,结合自己的经验,总结了如下发现。前端:html,jquery,angular后端:java,springmvc一、平常使用的post提交和接收方式前端使用jquery提交数据。$.ajax({
url:'/carlt/loginForm',
method: 'POST',
data:{&name&:&jquery&,&password&:&pwd&},
dataType:'json',
success:function(data){
});后端java接收:@Controller
public class UserController {
@ResponseBody
@RequestMapping(value=&/loginForm&,method=RequestMethod.POST)
public User loginPost(User user){
System.out.println(&username:&+user.getName());
System.out.println(&password:&+user.getPassword());
model(不要忘记get、set方法):
public class User {
//setter getter method
}后台打印:username:jquerypassword:pwd调用接口查看到的前端返回结果:二、使用angularJs的post方法提交&p ng-app=&myApp& ng-controller=&formCtrl&&
&form novalidate&
UserName:&br&
&input type=&text& ng-model=&user.username&&&br&
PassWord:&br&
&input type=&text& ng-model=&user.pwd&&
&button ng-click=&login()&&登录&/button&
&/p&js代码:var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http) {
$scope.login = function() {
url:'/carlt/loginForm',
method: 'POST',
data: {name:'angular',password:'333',age:1}
}).success(function(){
console.log(&success!&);
}).error(function(){
console.log(&error&);
});后台打印结果:username:nullpassword:null:查看前端:三、解决angular提交post问题。相信看过上面提到的哪怕文章的人已经知道怎么解决问题了吧。文中是更改了angular的提交方式,使得angular的提交数据方式更像jquery的。我试过,也是行得通的。然后我又试了另外一种方式。如下:前端不变,依然是:var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http) {
$scope.login = function() {
url:'/carlt/loginForm',
method: 'POST',
data: {name:'angular',password:'333',age:1}
}).success(function(){
console.log(&success!&);
}).error(function(){
console.log(&error&);
});后台变了,只是在User前加上@RequstBody,因为angular提交的是json对象:@Controller
public class UserController {
@ResponseBody
@RequestMapping(value=&/loginForm&,method=RequestMethod.POST)
public User loginPost(@RequestBody User user){
System.out.println(&username:&+user.getName());
System.out.println(&password:&+user.getPassword());
@RequestBody作用:
i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。使用时机:A) GET、POST方式提时, 根据request header Content-Type的值来判断:
application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);B) PUT方式提交时,根据request header Content-Type的值来判断:
application/x-www-form-urlencoded, 必须;
multipart/form-data, 不能处理;
其他格式,必须;说明:request的body部分的数据编码格式由header部分的Content-Type指定;四、解决了angular问题之后,发现jquery按照原来的方式提交post请求会报错(错误码415)。如下方式可以解决jquery提交问题:$.ajax({
url:'/carlt/loginForm',
method: 'POST',
contentType:'application/charset=UTF-8',
data:JSON.stringify({&name&:&jquery&,&password&:&pwd&}),
dataType:'json',
success:function(data){
});json对象转json字符串:JSON.stringify(jsonObj);以上就是解决angular的$http.post()提交数据时后台接收不到参数值问题的方法_AngularJS的内容,更多相关内容请关注PHP中文网()!共3篇0点赞收藏分享:.&猜你喜欢PHP中文网:独家原创,永久免费的在线,php技术学习阵地!
All Rights Reserved | 皖B2-QQ群:关注微信公众号Please enable JavaScript to view this page properly.
Want to keep up to date with all my lastest articles and tip?
This is my fifth article on file upload operations and second in AngularJS category. My
on AngularJS file upload used the native XMLHttpRequest() to post multiple files to a Web API controller class. However, I received few requests from developers asking me to share an example on AngularJS file upload using $http. Therefore, here I am going to show you how to use AngularJS $http service and FormData to post multiple files to a Web API controller for upload.
-----------------
If you are new to AngularJS, then I recommend you to read my first article that I have written for beginners.
-----------------
As you know, AngularJS $http is a service that provides functionalities to receive (get) and send (post) information to a remote HTTP server. Therefore, it’s a valid request, I must find a solution, and this is it.
Note: Since I am using FormData in my example here, I want you to know, that Internet Explorer 9 and its previous versions does not work with FormData.
Web API controller
This example uses a Web API controller to upload files. I have already created the controller before and I want you to check it. Click the below link and follow the steps to create the API.
What am I Doing in this Example?
I’ll first create a Custom directive in the scope. Why do I need a directive? An AngularJS directive attaches a special behavior to an HTML element, via the element’s attribute, name, classes etc. Please read the .
AngularJS built-in ng-model directive do not work with file input element. In-addition, we need a (event) listener that will help us track any changes in the elements behavior, for example, selecting files. To overcome this drawback, I’ll create a custom directive to listen to any change that occurs in the element. We can achieve this via the directives link option.
The Markup
&lt!DOCTYPE html>
&lttitle>AngularJS File Upoad Example with $http and FormData&lt/title>
&ltscript src="/ajax/libs/angularjs/1.4.4/angular.min.js">&lt/script>
&ltbody ng-app="fupApp">
&ltdiv ng-controller="fupController">
&ltinput type="file" id="file1" name="file" multiple
ng-files="getTheFiles($files)" />
&ltinput type="button" ng-click="uploadFiles()" value="Upload" />
I have attached an attribute called ng-files to the file input element. Now, I must create a directive in the controller matching the attribute, to get access to the file input element. The attribute has a function named getTheFiles() with a parameter $files. I’ll initialize the parameter $files in my directive and later call the function getTheFiles() using the controller’s scope, along with $files parameter.
The Directive and Controller
&ltscript>
angular.module('fupApp', [])
.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
link: fn_link
.controller('fupController', function ($scope, $http) {
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (value, key) {
formdata.append(key, value);
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: '/api/fileupload/',
data: formdata,
headers: {
'Content-Type': undefined
$http(request)
.success(function (d) {
.error(function () {
&lt/script>
I’ll divide the above script into two parts to explain. The first part is my directive with a name ngFiles (matching the file input attribute ng-files and the second part is the controller.
The Custom Directive “ngFiles”
The directive has the link option that takes a function.
link: function (scope, elm, attrs) { ... }
I have explicitly defined a function for the link and named it fn_link. The purpose of using the link option is to capture any changes that occur in the file input element. Now, how do we get the values? The answer is AngularJS $parse service. Usually, a $parse takes an expression and returns a function and our link option, also, needs a function to return. The parsed function onChange will have two parameters. The first parameter is the scope and the second will add the files details in $files variable through the event object.
The Controller
Now, we will access the files in our controller using getTheFiles() function. Its parameter $files will provide all the file details. Angular will call this function immediately when you select the files from a folder. The change callback in our directive will trigger this event. You can check the details of the selected files in your browser console.
$scope.getTheFiles = function ($files) {
console.log($files);
The information that you gather in this function will help you do some verification check on each file. I am not doing any verification check, however you can. You can check and allow specific file types only for upload or you can sum up the total size and check if it does not exceed the permissible limit etc.
console.log($files[0].type);
Once I get the details, I’ll run a loop using angular.forEach() to extract each file and save it in a FormData() object. The FormData object will provide the data to the $http service (using data property).
console.log(key + ' ' + value.name);
The second function uploadFiles in the controller is called when you click the upload button on the page. I have declared a variable request to accumulate all the information, before passing it to the $http service.
I have set the $http header as ‘Content-Type’:
undefined. The browser will set the type to multipart/form-data. You can confirm this by checking your browser's Developer Tools. If you are using Chrome, then press “Ctrl+Shift+I” keys to open developer tools. Choose the Network tab (second from left) to open it. Do this after you have uploaded the files. See the image.
If everything goes well according to your execution plan, $http service will send the files to your Web API controller class and it will do the rest.
That is it folks. If you have any queries, please leave a message below.
Thanks for reading.
Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Enter your email id
Delivered by
Share this article
Related Posts:24201人阅读
AngularJs实现Multipart/form-data 文件的上传
由于公司的需要,我们从java后台传统的JSP转向了使用前后台完全分离的模式来进行开发。后台完全提供接口,可供网页PC端和移动app端调取来获取数据。前台使用anjularjs来展示数据。
废话不多说了,直接进入主题吧。
一. 传统的表单提交文件是这样的
&from action="your url" method="post"
enctype="multipart/form-data"&
&input type="file" name="logo"&
&input type="submit" value="提交"&
后台springmvc的接受:
@ApiOperation(value = "上传文件", notes = "上传文件test", responseClass = "DataVo")
@RequestMapping(value = "/upload", produces = { "application/json" }, method =RequestMethod.POST )
public @ResponseBody DataVo upload(
@ApiParam(value = "logo", required = true) @RequestParam(value = "logo", required = true) MultipartFile logo,HttpServletRequest request){
if(logo!=null){
System.out.println(logo.getOriginalFilename());
二. anjularjs的处理文件上传
ng-controller="UploaderController" &
type="file" file-model="myFile" &
ng-click="save()" &保存&
这里要注意的是,因为是通过anjularjs的http请求来上传文件的,所以要让当前的request成为一个Multipart/form-data请求,anjularjs对于post和get请求默认的Content-Type header 是application/json。通过设置‘Content-Type’: undefined,这样浏览器不仅帮我们把Content-Type 设置为 multipart/form-data,还填充上当前的boundary,如果你手动设置为: ‘Content-Type’: multipart/form-data,后台会抛出异常:the current request boundary parameter is null。
通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我们的formdata object.
$scope.save = function() {
var fd = new FormData();
var file = document.querySelector('input[type=file]').files[0];
fd.append('logo', file);
method:'POST',
url:"your url",
headers: {'Content-Type':undefined},
transformRequest: angular.identity
.success( function ( response )
alert("uplaod success");
后台:同1中的后台
ps:上面的file的获取还可以通过:var file = $scope.myFile.同时要注意在js中 data: fd,不能像普通的参数一样写为:params:{ fd,…},具体的解释是:
params – {Object.&string|Object&} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters.
data – {string|Object} – Data to be sent as the request message data.
在GET方法中可以使用params ,在POST/PUT/PATCH/DELETE中不能使用params 来传递数据,要使用data来传递。
这样就实现了简单的anjularjs文件的上传,自己总结了一下,希望可以帮助到大家,加油!
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:35295次
排名:千里之外
评论:18条
(3)(3)(1)(1)(1)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'鍗氬?鍒嗙被锛

我要回帖

更多关于 angular post请求 的文章

 

随机推荐