Send blob file from javascript to C# asp.net - javascript

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.

Related

How do I upload a file using FormData and XmlHTTPRequest?

I'm trying to send a file from a web page to a php script using FormData, and the file isn't showing up in the $_FILES variable in the PHP page. Not sure if my error is on the JS side or the PHP side, or if I'm misunderstanding something deeper about the process.
Here's my code:
function uploadFile() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('success');
} else {
console.log('error');
}
}
};
xhr.open('POST','php/parsefile.php',true);
xhr.setRequestHeader("Content-Type","multipart/form-data");
var formData = new FormData();
formData.append("myfile", document.querySelector('#fileInput').files[0]);
xhr.send(formData);
}
<input type="file" id="fileInput">
<button onclick="uploadFile();">Upload</button>
Here's parsefile.php:
<?php
echo("Error: " . $_FILES["myfile"]['error'] . "\n");
echo("Name: " . $_FILES['file']['name'] . "\n");
When I upload a simple, small (64 bytes) text file, the console reads success, but the response from the server is just this:
Error:
Name:
What am I missing here? Thanks for any help anyone can provide.
I found two issues in your code:
In JavaScript code, you explicitly defined the "Content-Type" as "multipart/form-data". JS automatically gets the content type when you make the XHR Request.
In the 4th line of your PHP code, the key of the $_FILE is "file". You need to change it to "myfile", in order to make it work.
You can check my edited code below:
JS Code:
function uploadFile() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('success');
} else {
console.log('error');
}
}
};
xhr.open('POST','php/parsefile.php',true);
var formData = new FormData();
formData.append("myfile", document.querySelector('#fileInput').files[0]);
xhr.send(formData);
}
PHP Code:
<?php
echo "Name: ". $_FILES['myfile']['name'];
echo "Error: ".$_FILES['myfile']['error'];

how to add parameter into HttpContext.Request.Form from client side

I wanted to know how to add parameters into HttpContext.Request.Form via client side so that in the serve side i can get these data
i don't want to use ajax.
I tried the following but with no success:
javascript code:
var request = new XMLHttpRequest();
request.open("POST", window.location.host, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.append('skip', '10');
request.send(formData);
the asp.net mvc line of code:
var a = HttpContext.Request.Form.GetValues("skip");
but a is equal to null.
thank you all
Update:
I want to do something like datatable. In datatbles you can set draw,start, col_order etc. And you can get it with request into the server side. I want to know how can i do something like that.
You will need to combine data like this - "key1=value1&key2=value2&skip=10".
View
<button type="button" onclick="postData()">Post data</button>
<div id="result"></div>
<script>
function postData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("POST", "#Url.Action("PostData", "Home")", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2&skip=10");
}
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult PostData(FormCollection collection)
{
var key1 = collection["key1"];
var key2 = collection["key2"];
var skip = collection["skip"];
return Json($"key1: {key1}, key2: {key2}, skip: {skip}");
}
}
Screen Shots

C# aspx image upload using angular

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);
}
}

How to send a POST request to send BLOB data from client java script and receive it via MVC controller?

My current code:
Javascript
function pushFunc() {
mediaRecorder.requestData();
console.log(mediaRecorder.state);
mediaRecorder.ondataavailable = function (e) {
console.log("data size: ", e.data.size);
var encodeData = new Blob([e.data], { type: 'video/mp4' });
postBlobData(encodeData);
}
}
function postBlobData(blob) {
var formData = new FormData();
formData.append("blobContent", blob);
var request = new XMLHttpRequest();
request.open("POST", "/Device/Upload");
request.send(formData);
}
ASP.NET
**File: DeviceController.cs**
[HttpPost]
public string Upload(HttpPostedFileBase blobContent)
{
...
// return View();
}
The Java script code gets the blob from Media recorder and tries to post it down to the Controller.
Am i grabbing and posting blobs the way i should?
Should HttpPostedFileBase be used to receive the post request on the server side?
Fiddler Screenshot#1
Fiddler Screenshot#2
Fiddler Screenshot#3

unable to get response of ajax request in symfony2

I am new to symfony2. Basically I want to send a variable name to a file named sub.html.php. I am making an ajax request as following :
function onsub()
{
alert(document.getElementById('source').value);
var http=new XMLHttpRequest();
var name="rohit";
http.open("POST", {{path('task1')}}, false);
http.onreadystatechange = function()
{
alert(http.status);
if(http.readyState == 4 && http.status == 200)
{
alert('i m back');
}
else
{
alert('sorry');
}
}
http.send();
return false;
}
I have defined the route of task1 as follow:
task1:
pattern: /task1/
defaults: {_controller:AcmeTaskBundle:Task:task1}
and in TaskController I have defined task1Action as follow:
public function task1Action()
{
return $this->render('AcmeTaskBundle:Default:sub.html.php');
}
but I am unable to call the sub.html.php file anyhow. How can I call this file?
You can forward the request from the TaskController::task1Action() like so...
$response = $this->forward('VendorOtherBundleName:ControllerName:ActionName', array(
'some_variable' => $value
));
You can read more here

Categories

Resources