Is it possible to add multi media type to HTTP header? - spring

I want to make a request have both JSON and file
My controller :
#Authorize(roles={UserType.ADMIN,UserType.SCHOOL_ADMIN})
#RequestMapping(value="import",method=RequestMethod.POST)
public List<AddUserResponse>importUserBundle(#RequestBody AddUserRequest test,#RequestParam(value="userCsv")MultipartFile[] userCsv)
And got error when making a request :
Content type
'multipart/form-data;boundary=----WebKitFormBoundary62tvsTfonhCQ6HSl;charset=UTF-8'
not supported
Is there any way to make a request with both multipart/form-data and application/json media type?

Your AJAX call should be like this:
$.ajax({
url: '/importUserBundle',
type: 'POST',
data: {
userCsv: FileToSend,
test: JsonData
},
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
}
});
EDITED
processData:false Don't process the files
contentType:false Set content type to false as jQuery will tell
the server its a query string request.
Look at this for more info http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
Hope this will help

Related

Correct spelling in ajax POST

I have two verions of code I believe should do the same thing, but the first one works and other one doesn't (Post vars: agenti, week_, team_). I have searched for few examples of how to do it the other way and I am sure my example is similar.
What do I do wrong?
First:
$.post("index.html",
{
agenti: getItems(),
week_: week_array,
team_: team
},
function(data,status){
if (status = 'Success'){
alert('Aktuální řazení operátorů bylo úspěšně uloženo.');
} else {
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.');
}
Second:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "index.html",
data: JSON.stringify({agenti: getItems(), week_: week_array, team_: team}),
success: function (msg)
{
alert('Aktuální řazení operátorů bylo úspěšně uloženo.')
},
error: function (msg)
{
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.')
}
});
I want to do the second one because I need to specify content type and i couldn't figure how to do it in the first way.
Thanks you!
edit: I use IE; this code will be used only in IE.
so the first thing is that, no need to use JSON.stringify function, as the data accepts JSON objects, as well the string represented like a url (test1=1&test2=2...). So to use it like the following is ok.
data: {agenti: getItems(), week_: week_array, team_: team},
Also when you are using contentType: 'application/json' the GLOBAL $_POST variable is not being populated as it is being populated only for form-urlencoded data which is default value for contentType option, here you go with data from jQuery reference`
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
In order you like to use application/json, you can retrieve that information in PHP side using php input like this following. file_get_contents('php://input');
---Working Example---
Javascript:
$.ajax({
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost",
data: {agenti: 'test1', week_: 'test2', team_: 'test3'},
success: function(msg) {},
error: function(msg) {}
});
PHP:
// Retrieve the input
var_dump(file_get_contents('php://input'));
// Use $_POST var
echo json_encode($_POST);

Posting JSON using JQuery and to set HTTP content type - 'application /json'

I am using jquery to post Json data to server. However when I make a post request as below,
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
contentType : 'application/json',
success : successFunction
});
The http request header content type is not "application/json" even though I posting a json object.
Since it is not applcation/json, the server does not process the requset and returns 415.
Is there a way to set the header using javascript or jquery API?
Can you try this,
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: uri,
data: jsonStrJson,
dataType: "json",
success: function(json){
console.log(json);
}
});
"contentType" instead "contentTYpe" should also solve the problem. ;)
Also for setting http request header parameters you can try this approach:
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
headers : { 'Content-Type': 'application/json' }, //this line
success : successFunction
});

Extjs 4.2: How to send parameters properly in a Ext.Ajax.Request POST

I have to do a POST from my ExtJs script in order to delete something from my DB:
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
headers: {'Content-Type': 'text/html'},
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
params: {
"rolename" : rolename
},
scope:this,
success: received,
failure: function(){console.log('failure');}
});
when the post is sent i can see in the firebug the rolename in font but not as a param. I would like to show you another post (made with spring:form) relative to the user registration. If i inspect the post i can see the following:
(source: subirimagenes.com)
And i can get the parameters in my controller using #RequestParam.
But in the post that i have problems i can't see the parameters part, i can only see the Font(Fuente) part:
(source: subirimagenes.com)
As a consequence, my spring controller does not detect any parameter. Is it something wrong in my POST?
Thank you
The problem is that you are using the line headers: {'Content-Type': 'text/html'}, in your original question. This would set the content to text/html instead of the content being post data.
I solved it with the following code:
var rolename = 'myRol';
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
params: {
rolename: rolename
},
success: received,
failure: function(){console.log('failure');}
});
I'm using this in a Sencha Touch app. I had to add an extra config called jsonData and make it true or else nothing is passed to my endpoint url.
Ext.Ajax.request({
url: endpoint,
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : {add: formattedAddress, lat: latitude},
jsonData: true,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", 'yea');
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});

Sending POST request with Amplifyjs

I want to send this POST request by amplifyjs
amplify.request.define('createItem', 'ajax', {
url: baseApiUrl + '/create/?folderid={folderid}',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
after that, the execution will be something like this:
createItem = function (callbacks, folderid, itemdata) {
return amplify.request({
resourceId: 'createItem',
data : {
folderid: folderid,
data: itemdata
},
success: callbacks.success,
error: callbacks.error
});
};
"itemData" is already a JSON string. I keep getting the Bad Request status code.
If I change the API URL to:
baseApiUrl + '/create
And after that pass:
return amplify.request({
resourceId: 'createItem',
data :data,
success: callbacks.success,
error: callbacks.error
});
It works just fine, but I need to pass the Id as well. Maybe, I'm missing something here.
You need to combine folderid and itemdata into a single data object. When Amplify reads your data object it will extract the folderid property and place it in the URL of the request. Then it will POST the remaining properties of the data object.

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

Resources