Using a GET to POST data to a restfull api - javascript

I'm trying to do GET that retrieves data from a URL and then a POST to a RESTful api. The get call seems to work okay but the server sees nothing in the file parameter. I have verified that the GET call is return pdf stream data and that it is placing it in the FormData arg.
Here is the complete call
function upload(key, url){
var file;
/* get data from url */
$.ajax({
url: url,
type: 'GET',
async: false,
cache: false,
dataType : 'text',
contentType : 'application/pdf',
success: function( data ) {
file = data;
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
}
});
/* send data to api */
var data = new FormData();
data.append("key", key);
data.append("file", file); //<-- this has pdf stream data
$.ajax({
url: ROOT_URL + "/api/account/upload",
type: 'POST',
cache: false,
async: false,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: data,
success: function( data ) {
console.log("Uploaded!");
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
},
dataType: "json"
});
};
Here is the server side (grails + spring + jaxrs)
#POST
#Path('upload')
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces('application/json')
String upload(#Context HttpServletRequest request){
GrailsWebRequest w = WebUtils.retrieveGrailsWebRequest()
MultipartFile multipartFile = w.getRequest().getFile('file');
println("request:" + request)
println("multipartFile:" + multipartFile)
println("parameterMap:" + w.getRequest().getParameterMap() )
return ['okay':'uploaded'] as JSON
}
Which currently prints out:
request:org.grails.jaxrs.web.RequestWrapper#448593df
multipartFile:null
parameterMap:[file:[], key:[c07fc0974ebb4f3a8fc21e3d002152d4]]

Looks like when the POST call is happening, the variable file doesn't have a value yet. Since you are wanting everything after GET call to occur after the server has returned data, you should move that code into a separate function that is called upon success.

Related

.net Core send xlsx file as response for Ajax request

My web-application can only work with .xlsx-files. I created a function in my controller, which converts a .xls-file into an .xlsx-file. The conversion works totally fine. So whenever I try to open a .xls-file, I send it via Ajax request.
After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.
Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.
JavaScript:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
formData = new FormData();
formData.append("xlsfile", files[0]);
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: formData,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
Controller:
public IActionResult ConvertToXlsx(IFormFile xlsfile) {
//For simplification without conversion
//var xlsconverter = new XLSConverter();
//FileStreamResult response = xlsconverter.XLSConvert(xlsfile);
var path = $"wwwroot/temp/";
var filepath = Path.Combine(path, "test.xlsx");
MemoryStream x = new MemoryStream();
using(FileStream fs = System.IO.File.OpenRead(filepath)) {
fs.CopyTo(x);
}
return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
In the browser-network tab I get Status: net::ERR_CONNECTION_RESET
Am I missing a setting somewhere, which causes I simply can't respond with files?
If you want to pass file to action,try to use the following code:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: files[0],
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
And if you want to return file with content type,you can try to use:
public IActionResult ConvertToXlsx(IFormFile xlsfile)
{
return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

How can I send the image using Ajax

I want to know how can I send the image data to the server (Django app) using javascript ajax function.
Following is my code.
// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.
b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
filename: image_file_name,
image: b64_image,
};
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
jsondata = JSON.parse(data);
alert("File upload completed...");
})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
You have to use FromData for posting files using ajax .
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// success code .
}
});
You just need to make one change in your code.
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST', // changed from GET to POST
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
as GET is use to read and post is used to create.
you can read more about request methods.

Error post AJAX from Spring JAVA

I already created MVC spring and I want consume with SAPUI5 (javascript) with AJAX but I found an error "415 (Unsupported Media Type)". I use swagger in spring for test CRUD. in swagger, I success for insert data but failed in AJAX.
controller Spring:
#PostMapping(value={"/tesinsert"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(#RequestBody KasusEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabel(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
in javascript:
var data = {
"kodekasus":5,
"nama":"baru",
"isdelete":1,
"createdby":"hahaa",
"createddate":null,
"updatedby":"hihii",
"updateddate":null
};
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});
if I code above in AJAX, show error "415 (Unsupported Media Type)", if I add in AJAX show different error: "Response for preflight has invalid HTTP status code 403
":
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
}
How to solve this problem?
Thanks.
Bobby
Add dataType: 'json' in your ajax call:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});

Sending data from JQuery to C#, ASP.Net

I have a canvas in my .aspx form page where one can sign a signature, I would like to send the base64 data from the JQuery client side to the C# Asp.Net side. Here I want to upload this base64 data to a database.
(a couple things I tried)
Jquery:
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: '{ data: "' + base64 + '"}',
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 }); // another thing i tried
C#:
var d = Request.Params["data"];
The variable d is null when i put a breakpoint at it.
Does anybody see how I can tackle this hurdle, or make it easier?
(note: I do not have a lot of experience with JQuery)
Your JSON with base64 could be available as request body.
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
string text = reader.ReadToEnd();
}
If you replace
url: 'EvaluatieForm.aspx'
by
url: 'EvaluatieForm.aspx?data=' + base64
and remove
data: '{ data: "' + base64 + '"}',
then it will work.
Try this:
Just a small change in your existing code, used JSON.stringify to post data.
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
var objectToPasss = {data: base64};
var postData =JSON.stringify(objectToPasss );
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: postData,
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 });
Try this:
$("#savebtn").bind("click", function () {
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: {
sketch: $('#sketch')[0].toDataURL("image\png")
},
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
where
var d = Request.Params["sketch"];
The data argument in the jQuery ajax() function works in conjunction with the contentType. As you are setting it to application/json, then it stands to reason that data will be serialized, so setting the sketch variable seems about right.
With ajax you can try xhr.
maybe this thread helps you out! :)
How can I upload files asynchronously?

Jquery $.ajax not posting a string of data in ASP.NET MVC

I have a situation where I am building the json data to post dynamically. so I create it in a for loop and then attempt to use the $.ajax command, but on the server side the model is null. If I hard code the data section as would be normal, it works fine. I tried the same process with a simple model just to check and the same happens.
So this works:
$.ajax({
url: '#Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: {SharedSecret: 'Bob'},
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
But this doesn't:
var datastring = '{SharedSecret: Bob}';
$.ajax({
url: '#Url.Action("SetupQuestions", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
data: JSON.stringify(datastring),
success: function (data, status, xhr) {
$('#divMFAQuestion').html(data).fadeIn('slow');
},
error: function (xhr, status, error) {
alert("MFA Challenge Error (b): " + error);
}
});
Nor this:
var datastring = 'SharedSecret: Bob';
Any thoughts?
You have quotes around your entire JSON data structure:
var datastring = '{SharedSecret: Bob}';
JSON.stringify expects a JSON structure, so the quotes should only be around the string part for JSON.stringify to work:
var datastring = {SharedSecret: 'Bob'};
However, the reason that your AJAX call is not working is that the data parameter accepts a JSON data structure. JSON.stringify will serialize it as a string, which data does not expect. So you need to just pass the fixed datastring without JSON.stringify.
data: datastring

Categories