Retrieve binary data from C# with Ajax - javascript

I'm a bit new in web development and I can't achieve what I'm trying to do.
I have a Database with a table called "PI_Banners", where I store some images. This table stores an ID and a VARBINARY column that contains the binary data of the image.
What I'm trying to do, is to retrieve that data with an Ajax request to a C# function, and create a "img" tag using Data URI Scheme. Then append that new image to a div
This is what I got:
Ajax call:
$(document).ready(function() {
var dto = {};
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'BannerRotativo.aspx/devuelveBanners',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
responsedevuelveBanners(data);
},
error: errorResponse
});
});
Being "devuelveBanners" the C# function.
C# code:
public static string devuelveBanners()
{
DataReader DR;
DR = listaBanners();
//armaJson creates the Json string from the DataReader.
string strJson = GENERAL.armaJson(DR);
return strJson;
}
public DataReader listaBanners()
{
try
{
string strComando;
sqlCommand SQLC;
DataReader DR;
strComando = "SELECT banner_img FROM PI_Banners";
//sqlCon is the connection, and is open already.
SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
SQLC.CommandType = CommandType.Text;
DR = SQLC.ExecuteReader();
return DR;
}
catch (Exception ex)
{
throw ex;
}
}
When I parse the Json string back, and create the image:
function responsedevuelveBanners(data)
{
var datos = JSON.parse(data.d);
$("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
}
the image is created but doesn't show up, because it has this URL:
data:image/jpg;base64,System.Byte[]
I know I'm doing something terribly wrong trying to retrieve the json data this way, but I don't know how to achieve this!
Thanks in advance!

In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)
So using your code as example:
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));
Your WebApi method should be returning:
return Convert.ToBase64String(resourceByteArray);

Related

Call Webmethod to Fill DropDownList

I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}
Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.

Convert from JSON to array of objects

I'm trying to convert an array of Hazards(class that i created) to JSON,
this is my code:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
the returned data is like this :
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["
what i need to get is
{\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}
i dont know if it mind this is my server-side code by the way:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
You need to parse the JSON, using JSON.parse:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014

Why occur Internal server error in my ajax query?

I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'

controller can't return result in JSON object in ajax response

I have to call and fetch data from rest API with in every second. So I call the method with time 1 sec. As follows.
var myVar = setInterval(function(){ getData1() }, 1000);
Following is my Javascript function which call the controller.
function getData1(){
var url=CONTEXT_ROOT+"/login/getdashboarddata1";
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType: "json",
data:{},
success: function(data){
alert(data);
},
error: function(e){
//alert(e);
}
});
}
This is my controller code
#RequestMapping(value="/getdashboarddata1", method=RequestMethod.POST)
public JSONObject #ResponseBody getDashboardData1() throws JsonParseException, JsonMappingException, NullPointerException{
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/r_f22bc0ac1fe48bce/dataService/lastdata/";
String user = restTemplate.getForObject(url, String.class);
System.out.println("user: "+user);
JSONObject obj = null;
try {
obj = new JSONObject(user);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
If I run the program then jsp does not shows any alert. but if I change the return type of in controller to String then it shows proper JSON string in ajax response.
i.e. [{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
If i carry this, then I am unable to get data from JSON string.
please tell me what is my issue. or is there any other way to do this.?
You have json array
[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
Then access it using index:
data[0].sno
Simply return a String from getDashboardData1()
And then in AJAX success callback:
JSON.parse(data)[0]['sno'];
please tell me what is my issue. or is there any other way to do
this.?
You can't access attributes of a string literal, it has to be a json object.

Can't Send Base64 string To C# via AJAX

I am simply sending a base64 string thru ajax to an aspx page with C# code behind. The string never makes it to the C#. It always comes out empty.
The ajax is being sent in the post request and all other form fields post fine.
My string looks like: QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==
The method that sends the string to c# code behind is:
string signature = Request.Form.Get("newsig");
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap, signature);
The code behind:
string base64image = sig;
// Convert base64string to bytes array
var newbytes = Convert.FromBase64String(base64image);
Sometimes the base64 string is long - could this be the issue? Is there a better way of handling base64 strings in c#?
UPDATE: my ajax post method:
var localbase64string = localStorage["signature"];
var b64 = localbase64string.replace(/^data:image\/(png|jpg);base64,/, "");
var formData = new FormData($(this)[0]);
formData.append( 'newsig', b64);
var sendPost = 'http://xxx.xx/this.aspx';
$.ajax({
type: 'POST',
data: formData,
processData: false,
contentType: false,
timeout: 50000,
url: sendPost,
success: function(data){
alert('Sent!');
window.location.href = './../mainmenu.html';
}, error:function (){
alert("something went wrong!");
}
});
Another way to check what content you're sending is to use Request.Content.ReadAsStringAsync().Result in your C# receiving method.
Here's an example I put together quick:
C#:
public IHttpActionResult PostB64Test(string one, string two)
{
string b64 = Request.Content.ReadAsStringAsync().Result;
return Ok();
}
JS:
// here's an example url. I'm adding the base64 string to the POST body,
// and the other parameters in the query string.
var url = '/api/xxx/b64/?one=' +1 +'&two=' +2 +'';
var b64 = ""; // your base64 string e.g., "9j/4AAQSkZJRgABAg..."
$http.post(url, { b64: b64 });

Categories