C# aspx image upload using angular - javascript

I am using aspx page with angular js.
I've used angular and c# webmethod file upload.
I've tried to upload the image like used in web api.
When using web api, the image is uploaded successfully. When I try
with aspx, the webmethod is not hitting, but the result is coming with
the status success and also with the html page.
'
C# server side code didn't hit anyway.
The following is my Angular code which is working with Web api
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var form = new FormData();
if (file)
form.append("image", file);
var url = "Page.aspx/UploadImage";
xhr.open("Post", url, true);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function () {
reject(xhr.statusText);
};
xhr.send(form);
});
C#:
public static string UploadImage()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
httpPostedFile = HttpContext.Current.Request.Files["image"];
if (Path.GetExtension(httpPostedFile.FileName) == "" || !allowedImageTypes.Contains(Path.GetExtension(httpPostedFile.FileName), StringComparer.CurrentCultureIgnoreCase))
BLErrorHandler.ApplicationError("Invalid image type", ValidationError.ERR28);
}
}

Related

Send blob file from javascript to C# asp.net

Hi I have a problem when I send a blob file from client side to backend. The website is in C# web forms.
the code of javascript:
function (data) {
console.log(data.buffer);
window.open(URL.createObjectURL(new Blob([data.buffer], { type: 'application/pdf' }), "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10"));
PostBack(data);
<%-- $.unblockUI();--%>
delete data;
},
The POSTBACK function:
function PostBack(data) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.status);
console.log("staturi");
console.log(data);
// Typical action to be performed when the document is ready:
/*document.getElementById("MainContent_Label2").innerHTML = xhttp.responseText;*/
}
};
xhttp.open("POST", '<%= ResolveUrl("Default.aspx/testSS") %>', true);
xhttp.send(data);
}
Can you help me recive the PDF file and save it to server folder.
The backend function:
[WebMethod]
public string testSS(byte[] fileContent)
{
string straudioPath = "~App_Data/";;
FileStream objfilestream = new FileStream(straudioPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(fileContent, 0, fileContent.Length);
objfilestream.Close();
return "OK";
}
Thank you for your help in advanced.

File Upload through javascript

I am trying to send file in folder using javascript and my code is proper working in local machine but when i have upload the project in server this this not working
var formdata = new FormData();
var fileInput = $("#fileInput")[0];
formdata.append(fileInput.files[0].name, fileInput.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', ControllerUrl+'Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () { //This condition gone false and code is move ahead
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}

Stream webcam/audio and save it as a file on server - Apache

I am curious about implementing one feature into my small project.
Basically, what I want is when I go to one specific page, I want to start recording video and audio with my webcam, and save that session in my Apache server. Now, the thing is that I want to stream that as a data, and not record it and then send that file to a server. The reason for that is because when I am done with that page, I will be transferred to a different page and I will not have time to do upload the whole video.
I have found this on one git page,
<?php
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
And Javascript
var fileType = 'video'; // or "audio"
var fileName = 'ABCDEF.webm'; // or "wav"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
xhr('save.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
but I am not sure if that is the streaming solution (as I mentioned), and not record and then upload.
I am using PHP with some Javascript and have Apache as a server.

Image src not updating after setRequestHeader call

I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.

File uploads to asp.net web api using pure javascript via ajax

I am trying to do file uploads through ajax to my web api. My server side codes prove to be working cause I have managed to post files using a debugging Fiddler and it works fine. But I am failing to write successful javascript code that will be able to do the upload.
Below is my html code:
function sendImage() {
var data = new FormData();
var file = document.getElementById('upload').files[0];
data.append("image",file);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp_br=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp_br=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_br.onreadystatechange = function () {
if (xmlhttp_br.readyState == 4 ) {
var data = xmlhttp_br.responseText;
alert(xmlhttp_br.status+" "+data);
var file = JSON.parse(data);
}
}
xmlhttp_br.open("POST","http://localhost:59103/"+"api/upload/testUpload",true);
xmlhttp_br.setRequestHeader("Content-Type","multipart/form-data");
xmlhttp_br.setRequestHeader("filename", file.name);
xmlhttp_br.send(data);
}
<input name="UploadedImage" id="upload" type="file" accept="image/*">
<button onclick="sendImage()"> Upload Image </button>
<img id ="image">
My c# server side code is as follows
public async Task<IHttpActionResult> PostFile()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
Stream img = null;
string filename ="";
foreach (var file in provider.Contents)
{
filename = file.Headers.ContentDisposition.FileName.Trim('\"');
img = await file.ReadAsStreamAsync();
//Do whatever you want with filename and its binaray data.
}
bool status = UploadFileToS3(filename, img, "edu-media");
if (status)
{
return Ok();
}
else
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
}
Note that I am saving my files to aws s3 buckets and I don't want jQuery, only pure javascript.

Categories

Resources