Ajax-Post-Data-maxJsonLength-property-limit-execeed in javascript file - javascript

I am having problem while posting large amount of data from .js file to .cs file via ajax call.
Error is "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
$http({
url: exportexcelurl,
method: 'post',
data:JSON.stringify({componentid:componentid,city_id:cityid,industrysegment: indsegmentid, wf_activity: wf_activity_id, user: users }),
headers: {
"content-type": "application/json"
}
}).success(function (response) {
var downloadfileurl = webAppBase + "softcopyupload/download";
window.location = downloadfileurl + '?filename=' + response;
}).error(function (error) {
});

An alternate solution I found was calling the API in .cs file instead of pushing the data from .js to .cs file. And in .cs file I have set the jsonSerialization object's maxJsonLength to "2147483644". But the same configuration was not working in web.config file

Related

How can I post a json object and a file to asp.net server with fetch

I'm a bit stuck here, I'm trying to post a json object from my indexedDb simultaneously with a IFormFile object to the server. The method that accepts it looks like this:
[HttpPost]
public async Task<IActionResult> Create(BatchModel model, IFormFile vinFile)
{
//logic goes here
}
This method worked earlier, before I had to store my batchModels as Json objects, and were just posted straight from the form with a POST. A lot has changed since then, and now the client will upload it as soon as he gets online again from an offline state, with the following (simplified) method:
if (infoChanged === true) {
fetchPromises.push(
fetch('/Batch/Create/', {
headers: new Headers({
'Content-Type': 'application/javascript' //Tried this with multi-part/form
}),
credentials: 'same-origin',
method: 'POST',
body: batch //, vinFile
})
);
}
return Promise.all(fetchPromises);
For testing I tried to use the method with only the model filled, and the only thing I had to change was that I had to change in the C# code was adding a [FromBody] tag, but now I need the vinFile filled as well.
I tried it already with a FormData object, appending the batch and the vinFile with the same name as in the Create function. But that would result in both variables as null.
The key feature you need to look at is your header. You can change your response to JSON if you do header: { Content-Type: "application/json" }
You want something like this: You need to configure the type yourself.
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); });
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How to write JSON array to file in node.js and request it again client side

I'm trying to create a drag-and-drop table with save and load functionality. I'm using code from REDIPS.drag.
When using the REDIPS save function the table content is returned, client side, to the console and alert like this:
[["d2",2,2,"blue","A1"],["d1",4,5,"blue","A2"],["d3",3,2,"blue","A3"],["d4",1,4,"blue","A4"]].
I've tried a few different ways to POST the data to node and write it to file.
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content},
dataType:'json',
contentType: "application/x-www-form-urlencoded"
});
App.js
var testjson = req.body;
var tablestringify2 = JSON.stringify(testjson);
fs.writeFile('views/test.json', tablestringify2,'utf8', function (err) {
if (err) {
// append failed
} else {
// done
}
})
The data saved to file is:
{"table_content":"[[\"ns1.8b\",3,1,\"\",\"ns1.8b\"],[\"ns3.1\",4,2,\"\",\"ns3.1\"]]"}
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: table_content,
dataType:'json',
});
The data is saved to file as:
{"[":{"\"ns1.8b\",3,0,\"\",\"ns1.8b\"":{"\"ns3.1\",3,2,\"\",\"ns3.1\"":""}}}
When I use a GET, I parse the data which returns;
{ table_content: '[["ns1.8b",3,1,"","ns1.8b"],["ns3.1",5,3,"","ns3.1"]]' }
or
{[:{"ns1.8b",3,0,"","ns1.8b":{"ns3.1",3,2,"","ns3.1":""}}}
Either form cant be loaded back into the table using the REDIPS load function.
Is there any way I could get the data in the following format;
[["ns1.8b",3,0,"","ns1.8b"],["ns3.1",3,2,"","ns3.1"]]
...returned on the client side?
Or would it be possible to save it to file like that?
Perform the stringify at the client side:
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content: JSON.stringify(table_content)},
dataType:'json',
});
At the server side you should be able to access req.body.table_content which will be the (JSON) string representation of the array.

Upload files to Dropbox using a Dropbox Core API in Javascript

I am working on a simple chrome-extension that needs to upload files to the user's dropbox folder. I am using the simple AJAX requests as mentioned below to upload files, however it works for files with extensions such as .txt, .json, .c, etc i.e. files whose mime type is of type text/plain or similar type but all other file types such as pdfs, image files etc get corrupted and produce blank contents. What am I missing in uploading the files the correct way.
function startUpload()
{
var folderPath = $(this).closest('tr').attr('path')+'/';
var file = $("#upload_file")[0].files[0];
if (!file){
alert ("No file selected to upload.");
return false;
}
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
uploadFile(folderPath+file.name,evt.target.result,file.size,file.type);
}
}
//function to upload file to folder
function uploadFile(filepath,data,contentLength,contentType){
var url = "https://api-content.dropbox.com/1/files_put/auto"+filepath;
var headers = {
Authorization: 'Bearer ' + getAccessToken(),
contentLength: contentLength,
};
var args = {
url: url,
headers: headers,
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: contentType,
data : data,
dataType: 'json',
success: function(data)
{
getMetadata(filepath.substring(0,filepath.lastIndexOf('/')),createFolderViews);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}
I believe the issue is reader.readAsTextFile(file, "UTF-8"). If the file isn't a text file, this will misinterpret the contents. I think you want reader.readAsBinaryString or reader.readAsArrayBuffer. (I haven't tested it myself.)
EDIT
After testing this myself, I found that readAsArrayBuffer is what you need, but you also need to add processData: false as an option to $.ajax to prevent jQuery from trying to convert the data to fields in a form submission.
Also be sure to use dataType: 'json' to properly parse the response from the server.

this operation requires iis integrated pipeline mode

I have ajax call on my aspx page as:
$.ajax({
url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData",
data: JSON.stringify({
'_OrderNumber': $("#txtOrderNumber").val(),
'_PackageNumber': $("#lblPackageNumber").html(),
'_Height': $("#txtPackageHeight").val(),
'_Width': $("#txtPackageWidth").val(),
'_Lenght': $("#txtPackageLenght").val(),
'_Weight': $("#txtPackageWeight").val(),
'_ReferanceNumber1': $("#txtPackageReferanceNumber1").val(),
'_ReferanceNumber2': $("#txtPackageReferanceNumber2").val(),
'_ReferanceNumber3': $("#txtPackageReferanceNumber3").val(),
'_ReferanceNumber4': $("#txtPackageReferanceNumber4").val(),
'_ReferanceNumber5': $("#txtPackageReferanceNumber5").val(),
'_PackageType': $("#ddlAddPackageType").val()
}),
contentType: 'application/json;',
dataType: "json",
type: 'POST',
cache: false,
success: function (Data) {
//whatever operation to be performed
},
error: function (err) {
alert("Error in Saving.Please try later." + JSON.stringify(err));
}
});
On cs page my addUpdatePackageData method is:
[WebMethod()]
public static ShipStationIntegration[] addUpdatePackageData(string _OrderNumber, string _PackageNumber, string _Height, string _Width, string _Lenght, string _Weight, string _ReferanceNumber1, string _ReferanceNumber2, string _ReferanceNumber3, string _ReferanceNumber4, string _ReferanceNumber5, string _PackageType)
{
System.Collections.Generic.List<ShipStationIntegration> lst = new List<ShipStationIntegration>();
try
{
lst = bindPackageListFromPageMethod();
return lst.ToArray();
}
catch (Exception)
{
return lst.ToArray();
}
}
This returns correct list.
Butafter getting responce it always goes in error block of ajax as and gives error as:
I am not understanding what is wrong in it?
I also tried with:
contentType: 'application/json; charset=utf-8',
But still error was there.
Please help me.
If you are using the VS 2010 integrated web server (Cassini), it does not support Integrated Pipeline mode. You'll need to download IIS Express and set your project to use it instead.
When your return from a webmethod and the response format should be JSON the response pass to a httpModule that serialize the response into JSON and try to execute Response.Headers.Add("Content-type", "application/json"); BUT this way to add http headers are not supported by Cassini because this way needs Integrated Pipeline mode and as #Kevin says:
Cassini does not support Integrated Pipeline

upload file to dropBox using /files_put javascript

Is it possible to upload a local file to dropbox using http put method ?
i am uploading a file but it is without body ? ( "bytes": 0 )
how can i add a content to my file ?
my code is the following :
$scope.uploadHtmlFile = function() {
$http({
method: 'PUT',
url: 'https://api-content.dropbox.com/1/files_put/dropbox/test.txt?access_token='+ localStorage.getItem('accessToken')
}).success(function(data,status,headers,config){
console.log(data);
console.log('file uploaded successfully');
}).error(function(data,status,headers,config){
});
}
my file is successfully uploaded but with no content ? it is empty !!
the documentation is a little confusing to me : https://www.dropbox.com/developers/core/docs#files_put
#smarx : i was making an empty HTTP PUT request, and i ended up by solving my issue this way:
$scope.uploadHtmlFile = function() {
var data = "This is a file upload test ";
$http({
method: 'PUT',
url: 'https://api-content.dropbox.com/1/files_put/dropbox/test.html?access_token=' + localStorage.getItem('accessToken'),
data: data
}).success(function(data, status, headers, config) {
console.log(data);
console.log('file uploaded successfully');
}).error(function(data, status, headers, config) {
});
}
thanks for your feedback !
I don't see anywhere in your HTTP call where you're actually passing a body. It seems like you're making an empty PUT request?
(Or maybe there's just something here about AngularJS that I don't understand, and you're adding a body somewhere else?)

Categories

Resources