I've been trying to solve this for days and I can't find out what's going wrong. I'm a beginner on C# and javascript so that might be a big factor. So I record a video from my webcam using RecordRTC.js. Getting the recordedBlob from that, I want to save it somewhere in my Solution.
Here's my code in sending the blob in the code-behind:
recordedBuffer.replace('data:video/mp4;base64,', '')
$.ajax({
type: 'POST',
url: 'BasePage.aspx/UploadVideo',
data: '{ "video" : "' + recordedBuffer + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert("SUCCESS: " + data.d);
}, error: function (xhr, err) {
alert(xhr.responseText);
}
});
And then in C#:
[WebMethod()]
public static string UploadVideo(string video)
{
DateTime date = DateTime.Now;
string fileNameWitPath = MapPathStatic("~/Gallery/Videos/" + date.ToString("yyyyMMddHHmmss") + ".mp4");
//MapPathStatic is a static version I made of Server.MapPath()
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(video);
bw.Write(data, 0, data.Length);
bw.Close();
return fileNameWitPath;
}
}
}
The file is being created in the proper file. But when I try to play it, it said it cannot render the file. This is only 1-2 second video. So the video is being corrupted midway? What am doing wrong? Why is it not rendering correctly.
I've also found solutions using PHP to save the file but I really would like to use C# for this.
Any help or suggestions would be appreciated!
Related
I am creating a signature on the client side in javaScript and then trying to send the result to the code behind(c#) via ajax. The resulting array I am trying to pass is of type uint8clampedarray and I am unable to do, with the code behind method never being hit.
It is hitting the Page Load method but not the SetSignature method.
javaScript
var signatureByteArray = signature.getSignatureImage();
SendArrayViaAjax(signatureByteArray);
function getSignatureImage() {
return ctx.getImageData(0, 0, canvas.width, canvas.height).data;
}
function SendArrayViaAjax(signatureArray) {
var sigArray = JSON.stringify( signatureArray);
$.ajax({
type: "POST",
data: { array: sigArray },
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/OHS/SOP/SOPSignOffs.aspx/SetSignature",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has taken place");
}
});
}
code behind
[WebMethod]
public static string SetSignature(string[] array)
{
var x = array[2];
return "success";
}
My question is how do I send the array as it is as uint8clampedarray via ajax and how do I retrieve it in c#? Or is there a better way?
ctx = canvas.getContext("2d");`
is how I am getting the the Canvas element.
The generation of thew signature works really well, it is just sending it back to C# which is the problem.
The solution I found was to generate the canvas image data differently (old way).
Generate Image Differently
function getSignatureImage() {
//return ctx.getImageData(0, 0, canvas.width, canvas.height).data;
var pic = canvas.toDataURL("image/png");
pic = pic.replace(/^data:image\/(png|jpg);base64,/, "")
return pic;
}
And then in then ajax function
$.ajax({
type: "POST",
data: '{"imageData" : "'+ signatureImage + '" }',
....
And then in the code behind
public static string SetSignature(string imageData)
{
string filePath = HttpContext.Current.Server.MapPath("Signature.png");
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here
I have an issue with my API call to my download method.
Here is the JS code I'm using, it's used with knockout:
self.downloadFile = function(file) {
// Ajax Call Get All Leave Records
$.ajax({
type: "POST",
url: "/api/v1/CompanyFilesApi/DownloadFile",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ko.toJSON(file),
success: function (data) {
console.log("Here is your file");
},
error: function (error) {
alert(error.status + " <--and--> " + error.statusText);
}
});
// Ends Here
};
And here is my API solution:
public HttpResponseMessage DownloadFile(FileModel file)
{
var path = file.FilePath;
var result = Request.CreateResponse(HttpStatusCode.OK, file.FileName);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
The file parameter contains the file path and name.
Can anyone tell me what I'm doing wrong?
The response is always ok but it goes on the error branch and the file is not open. The files are PDF, Excel, Word.
EDIT 2:
You can use target="_blank" instead of download to open the pdf in a new tab.
To modifify the 'a' tag :
$("#your-a-tag-id").attr("href", "data:application/octet-stream;base64," + fileDataString);
EDIT:
This could also help you
link
One solution would be to encode to base64 and use it as such :
...
dataType: "application/octet-stream;base64"
...
then put the response data in a href
<a href="data:application/octet-stream;base64,/*YOUR FILE DATA*/" download="your filename">
I'm not sure how to deal with that in your API though.
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);
I am trying unsuccessfully to extract the formatted_address property.
The following web service logs the JSON below to the console. I cannot get the formatted address using returnedData.d.results[0].formatted_address.
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
console.log(returnedData);
}
});
The format of the json is the exact same as the format over here at Google.
Edit
Darin pointed out that I was contradicting myself: the web service wraps up everything in the link above in a d object, I failed to mention that.
Further edit
Here is the web service:
[WebMethod]
public static string ReverseGeocode(decimal latitude, decimal longitude)
{
// Create the web request
string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude +"&sensor=true";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
and here is the javascript:
/Gets the current location of the user
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
alert(returnedData.d[0].results[0].formatted_address);
console.log(returnedData);
}
});
Have you tried using returnedData.results[0].formatted_address without the .d. node. That does not exist!
remove the ".d"
returnedData.results[0].formatted_address
but doing this you are always getting the first node only
The answer to this issue turns out to be that the web service is returning a string, instead of json. The built-in javascript serializer does not get used. The eval keyword or something more secure needs to be used. As it happens I ended up using the Google Maps Javascript API and that was much easier anyway.