Error while sending List<String> in multipart request - spring

I am trying to send a multipart request to a controller service which looks like following
#RequestMapping(value="/uploadFile", method=RequestMethod.POST)
public void uploadApk(#RequestPart("fileName") String fileName,
#RequestPart("md5") String md5,
#RequestPart("userList") List<String> userList,
#RequestPart("file") MultipartFile file){
...
...
}
The ajax request for calling the above function is
var formData = new FormData();
formData.append("fileName",imgfileList[0].name);
formData.append("md5",md5);
formData.append("userList",userList);
formData.append("file", imgfileList[0]);
$.ajax({
url: urlPost,
type: "POST",
data: formData,
dataType: "json",
processData: false,
enctype:'multipart/form-data',
headers: {'Content-Type': undefined},
success: function(data)
{
alert("File Uploaded!");
}
});
I have tried to follow this link
But i am getting the following error.
{"timestamp":1434485164651,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/octet-stream' not supported","path":"/uploadFile"}
I tried to debug the error and found that the error was coming only for "#RequestPart("userList") List userList". That is the error appears only while sending an array of strings.
How do I solve the problem ?

Related

Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax

Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
    if (request.status == 200) {
      toastr.success('Yai! Saved successfully!');
    } else {
      toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
  };
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)

Does Spring Form Backing support takes null as a value of an entity

I have an entity User[userid, name , age]
Now from jsp I am hitting ajax like this:
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: "userid=" + userid+ "&name=" + name + "&age=" + age,
success: function (response) {
alert("success");
}
And my controller is:
#ResponseBody
#RequestMapping(value = {"saveUser"}, method = {RequestMethod.POST})
public String submitProblem(HttpServletRequest req, User user)
{
//backend codes
}
My question is when I am sending name="ABC" , age="24" and id=32;
everything is fine.
But "The request sent by the client was syntactically incorrect." response comes if I am sending id=null.
Please help me to know the issue.
try to use json data in your ajax request first you can use
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: {'userid': userid, 'name': name, 'age' : age},
success: function (response) {
alert("success");
}
and try to use corectly with spring i cant help you ive never use spring also your error is type of id
if you convert your id on string maybe this will work because your age work try to do
userid = userid.toString();
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: "userid=" + userid+ "&name=" + name + "&age=" + age,
success: function (response) {
alert("success");
}

Trying to send multiple parameters to ASP.NET webAPI post method results server error 500

Iam trying to send multiple parameters with complex datatype to POST method in WebAPI but it fails with 500 server error. I will be greatful if somebody help me finding what is missing ?
Ajax:
var x={}
var y={}
$.ajax({
cache: false,
type: "POST",
data: JSON.stringify({xDto:x,yDto:y}),
url: "/api/Info/PostInfo",
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function(data) {
}
error: function(data) {
alert(JSON.stringify(data));
}
})
Action:
public IHttpActionResult PostInfo(InfoDto xDto,InfoDto yDto)
{
//post xDto and yDto to db
}
I would change the API Parameter to an InfoDto array and retrieve it from the body:
public IHttpActionResult PostInfo([FromBody]InfoDto[] xDtos)
{
}
You also have to change your JavaScript to something like this:
data: JSON.stringify([x, y])

Error when calling the URL for saving JSON in database: String is too long

This is the method from the controller api :
[HttpPost]
public void SaveFloor(int floorID, string json)
{
Floor floor = db.FloorSet.Find(floorID);
floor.SavedJson = json;
floorRepository.Update(floor);
floorRepository.Save();
}
Then I made an ajax call to pass the URL.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId + "&json=" + Json,
type: "POST",
dataType: 'json',
success: function (data) {
alert('success');
}
});
}
I'm trying to save JSON in database (datatype: nvarchar(MAX)), when I call the URL that executes the saving, I get this error Error HTTP 404.15 - Not Found and it says that the filter module applications is configured to deny a request if the string is too long.
So, what should I do? the JSON that I generate is in fact supposed to be too long, and that's the purpose. Please help.
Send the JSON string as the POST body not as part of the URL. Send it as text and json_decode on the server.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId,
type: "POST",
data: Json,
dataType: 'text/html',
success: function (data) {
alert('success');
}
});
}

Reading JSON values in servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 3 years ago.
I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String.
I am not sure whether data is getting posted or not. Also, I want to verify login and password by fetching it from json object.
Heres the code snippet:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
function doajax(){
var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data:{ "mobileno":mobileno, "fullname":fullname},
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
}
</script>
My servlet side code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
String message=null;
JSONObject jObj = new JSONObject(request.getParameter("jsondata"));
Iterator<String> it = jObj.keys(); //gets all the keys
String Name=null;
String mobileno=null;
while(it.hasNext())
{
String key = (String) it.next(); // get key
if(key.equals("fullname"))
Name = (String)jObj.get(key);
else if(key.equals("mobileno"))
mobileno=(String)jObj.get(key);
}
if(Name=="abc" && mobileno=="123" )
message="success";
else
message="fail";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", message);
out.println(jsonObject);
The datatype attribute of the jQuery.Ajax function states the following:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
So, what you are sending is not a JSON string. What you are sending is plain old request data.
You can get this data in your servlet using:
String mobileno = request.getParameter("mobileno");
You do not need to stringify the data ... just send it as a plain old javascript object ... by specifying datatype as json ... jquery will figure out how to pack the data in the request
No need to change anything on server side
So if your AJAX call becomes:
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data: jsondata,
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
Retrieve them in the servlet as
String fname = request.getParameter("fullname");
String mobileno = request.getParameter("mobileno");
I think you will need to be careful about case sensitivity
EDITED
I see that you Can you change your script to be as follows.
<script type="text/javascript">
function doajax(){
var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;
var postReqData = {}; // Create an empty object
postReqData['mobileno'] = mobileno;
postreqData['fullname'] = fullname;
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data: postReqData,
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
}

Resources