How to pass blob value through ajax call in javascript? - javascript

We are Generating blob value and want to get it inserted into the database through SQL Server.
We are able to pass the blob value and through the help of Ajax call we are trying to get it to insert but we are receiving the error Uncaught (in promise) TypeError: Failed to execute 'array buffer on 'Blob': Illegal invocation code. And in WebServices, we are passing it as byte value byte[] BLOB while in SQL we are using var binary(max) to store the value.
async function pdfhandler() {
let pdfBlob = '1';
var mystring = "Hello World!";
pdfBlob = new Blob([mystring]);
updateblobdata(pdfBlob);
console.log(pdfBlob);
}
function updateblobdata(blobvalue) {
debugger;
/// Insert Blob into Database ///
console.log('updateblobdata called');
const urlParams = new URLSearchParams(window.location.search);
const myParamtag = urlParams.get('104');
const mymodelval = urlParams.get('DuganHosp-0002');
var wonumval = '104'; var tagnumval = 'DuganHosp-0002';
var Modeval = 'U';
var BLOBval = blobvalue;
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: {
WoNum: wonumval,
Tagnum: tagnumval,
BLOB: BLOBval,
Mode: Modeval,
},
method: 'post',
dataType: 'json',
contentType: false,
processData: false,
cache: false,
success: function (data) { },
});
}

You can send files only with content-type: multipart/form-data.
function updateblobdata(blobvalue) {
const formData = new FormData();
formData.append('blob', blobvalue);
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: formData,
method: 'post',
dataType: 'json',
contentType: 'multipart/form-data',
processData: false,
cache: false,
success: function (data) { },
});
}

No Still its not working.Its not coming to this point for blob value.
[WebMethod]
public void UpdateHtmlBLOBContent(string WoNum, string Tagnum, byte[] BLOB, string Mode)
{
string htmldoc = null;
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConStr1"]))
{
SqlCommand cmd = new SqlCommand("TestTool_PrototypeprocBlobRun", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Workorder", WoNum);
cmd.Parameters.AddWithValue("#Equipment", Tagnum);
cmd.Parameters.AddWithValue("#HTML_blob", BLOB);
cmd.Parameters.AddWithValue("#MODE", "U");
con.Open();
int i = cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
htmldoc = "Success";
}
dr.Close();
}
Context.Response.Write(htmldoc);
}
}

Related

application/json content type store location

the result of content type : "application/x-www-form-urlencoded" stored in Request.Form in Asp MVC.
but for "application/json" i cant find the store location
here is the code that i use:
ajax part
// reading form data
var form = $("form")[0];
var formData = new FormData(form);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var data = JSON.stringify(object);
// ajax part
// POST application/json; charset=utf-8
$.ajax({
type: "POST",
url: "#Url.Action("FormSubmit","Home")",
data: data,
dataType: "json",
async: true,
contentType: "application/json",
processData: true,
success: function(result) { },
error: function(result) { }
});
Controller Part
[HttpPost]
public ActionResult FormSubmit(string input1, string input2)
{
var httpContext= HttpContext;
var response = Response;
var request = Request;
throw new NotImplementedException();
}
You can use controller like this:
[HttpPost]
public ActionResult SomeAction(string data)
{
List<YOUR_MODEL_CLASS> payloadObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YOUR_MODEL_CLASS>>(data)(modelData);
// process your data
}
Found the answer
i just need to read post Payload
here is the code
[HttpPost]
public ActionResult FormSubmit()
{
Request.InputStream.Position = 0;
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
string reqString = Encoding.ASCII.GetString(reqMemStream.ToArray());
throw new NotImplementedException();
}

jQuery.ajax() : send blob object to Spring REST

How to send by jQuery.ajax() an object containing types String and Blob and receive it on the Spring REST side by #RequestBody myModelClass?
JavaScript:
function savePicture() {
var img = canvas.toDataURL('image/jpeg');
var blob = new Blob([img], {type: 'image/jpeg'});
var d = new Date();
var cd = (d.getUTCMonth()+1) + "/" + d.getUTCDate() + "/" + d.getUTCFullYear();
var fd = new FormData();
fd.append('name', 'mypicture');
fd.append('author', 'Kate');
fd.append('createdDate', cd);
fd.append('content', blob);
$.ajax({
type: "POST",
url: "/send",
data: fd,
processData: false,
contentType: 'application/json',
cache: false,
timeout: 600000,
success: function (data) {
console.log(data);
},
error: function (e) { }
});
}
Spring REST (The function to receive the object from ajax() and save to the database.):
#PostMapping(value="/send")
public ResponseEntity<?> sendPictureToDatabase(#RequestBody Picture picture, Errors errors) throws IOException {
pictureService.savePicture(picture);
AjaxResponseBody result = new AjaxResponseBody();
result.setMsg("success");
result.setResult(pictureService.getAllPictures());
return ResponseEntity.ok(result);
}
My model:
#Entity
public class Picture {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable=false)
private Long id;
#Column(nullable=false)
private String name;
#Column(nullable=false)
private String author;
#Column(name="CREATED_DATE", nullable=true)
#Convert(converter = LocalDateAttributeConverter.class)
private LocalDate createdDate;
#Column(nullable=false)
#Lob
private String[] content;
//...
}

data.d does not return any data and says undefined

trying to retrieve data from data.d but not able to access data from data.d as it says data.d is undefined
this is my jquery function
$("body").on("click", "#aProfile", function () {
$("#divProfile").show();
$("#divChangePassword").hide();
$("#txtProfileUserName").val('<%=HttpContext.Current.Session["UserName"].ToString()%>').prop('disabled', true);
var UserName = $("#txtProfileUserName").val();
$.ajax({
type: "POST",
url: "StudentPanel.aspx/GetUserDetails",
data: JSON.stringify({ UserName: $('#txtProfileUserName').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
$('#txtProfileName').val(data.d.Name);
$('#txtProfileEmail').val(data.d.Email);
$('#txtProfileGender').val(data.d.Gender);
$('#txtProfileContact').val(data.d.Contact);
$('#txtProfileCountry').val(data.d.Country);
$('#txtProfileState').val(data.d.State);
$('#txtProfileCity').val(data.d.City);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
$('#txtProfileCountry').prop('visible', false);
$(".Profile").prop('disabled', true);
});
this is my c# function
[System.Web.Services.WebMethod]
public static User GetUserDetails(string UserName){
User u = new User();
string CS = ConfigurationManager.ConnectionStrings["BBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS)){
SqlCommand cmd = new SqlCommand("spGetSISUserByName",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#UserName",
Value = UserName
});
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
u.Name = dr["Name"].ToString();
u.UserName = UserName;
u.Email = dr["Email"].ToString();
u.Gender = dr["Gender"].ToString();
u.Contact = dr["Contact"].ToString();
u.Country = dr["Country"].ToString();
u.State = dr["State"].ToString();
u.City = dr["City"].ToString();
}
}
return u;
}
I want to assign value from data.d but it returns undefined data.d
Problem solved
Inside ~/App_Start/RouteConfig.cs I changd :
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
or you can just comment the line and its done

Web service 404 always due complex types

I'm having problem passing some complex data in a call, one type is HTML, another one is stringify Json.
REQ_Description = HTML
REQ_Services = JSON.stringify(SomeData)
Here is my code
SERVER
Interface
[WebGet(UriTemplate = "InsertPedidos/{requestId}/{categorie}/{projectType}/{sla}/{possibleDate}/{desireDate}/" +
"{desireJustification}/{services}/{description}/{workflowState}/{tempId}",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json)]
int InsertPedidos(string requestId,
string categorie, string projectType, string sla, string possibleDate, string desireDate,
string desireJustification, string services, string description, string workflowState,
string tempId);
Implementation
public int InsertPedidos(string pid, string requestId,
string categorie, string projectType, string sla, string possibleDate, string desireDate,
string desireJustification, string services, string description, string workflowState,
string tempId)
{
var data = new LinqToRequestsContext(Elevate.RequestsUrl);
var ped = data.GetList<FDM_MAINREQUESTSMAINREQUESTS>("FDM_MAINREQUESTS");
ped.ScopeToFolder(_folder, false);
var insert = new FDM_MAINREQUESTSMAINREQUESTS()
{
REQ_RequestID = double.Parse(requestId),
REQ_Categorie = double.Parse(categorie),
REQ_ProjectType = double.Parse(projectType),
REQ_SlaOnDate = int.Parse(sla),
REQ_RequestDate = DateTime.Now,
REQ_PossibleDate = DateTime.Parse(possibleDate),
REQ_DesireDate = DateTime.Parse(desireDate),
REQ_DesireJustification = desireJustification,
REQ_Services = services,
REQ_Description = description,
REQ_Worflow_State = int.Parse(workflowState),
REQ_Origin = 0,
Title = tempId,
REQ_CRU_DateCreated = DateTime.Now,
REQ_CRU_UserCreated = SPContext.Current.Web.CurrentUser.Email
};
ped.InsertOnSubmit(insert);
data.SubmitChanges();
return 1;
}
Client Side
function InsertOrUpdatePedido(id, how) {
$("#img_Progress").show();
var $treemain = $("#tt"); // the source tree
var data = $treemain.tree("getData", $treemain.tree("getRoot").target);
var jdata = JSON.stringify(data);
if (how > 0) {
this.litem = list.getItemById(how);
} else {
var formData = {
requestId: id,
categorie: $("#sel_categories option:selected").val(),
projectType: $("#sel_projecttype option:selected").val(),
sla: $("#tipoSla").val(),
possibleDate: $("#dataPrevista").val(),
desireDate: $("#dataDesejada").val(),
desireJustification: $("#justificacaoPedido").val(),
services: jdata,
description: $("#weditor").Editor("getText"),
workflowState: "1",
tempId: tempid
};
JSON.stringify(formData);
jQuery.ajax({
cache: false,
type: "GET",
url: "/_vti_bin/APP/Requests.svc/InsertPedidos",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: formData,
success: function(ret) {
if (ret === 1) {
MessPopups("s", "Pedido efetuado corretamente");
}
}
});
}
}
Can someone give me a clue? i tried to decodeURI() for complex fields because is passing "%2%2....", tried also to stingify DATA, no luck. Is there any other way? I think I wrote the code to complex and not "KISS".
I´m Stuck
Thank You
Joao

Cant get array from ajax

I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me?
Unknown web method GetListofCompanies.
Parameter name: methodName
Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetListofCompanies(string name) {
var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
JS:
var name = "";
$.ajax({
url: "Company.aspx/GetListofCompanies",
type: "post",
data: { name: name },
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
$("#txtName").autocomplete({
source: responseArray
});
}
});
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;
[WebMethod]
public static string GetListofCompanies(string name)
{
List<string> companies = new List<string>();
companies.Add("Company1");
companies.Add("Company2");
companies.Add("Company3");
companies.Add("Company4");
companies.Add("Company5");
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
// JS
function request() {
var name = "";
var data = { name: name };
$.ajax({
url: "Default.aspx/GetListofCompanies",
type: "POST",
contentType: 'application/json',
data: JSON.stringify(data)
}).success(function (data) {
// do your stuff here
})
.fail(function (e) {
alert("Error");
});
}

Categories