26631

How do I use AJAX to upload files to ASP.NET?

I am trying to upload files using AJAX to ASP.NET. I have this Javascript:

var xhr = new XMLHttpRequest(); for (var i = 0; i < files.length; i++) { xhr.open('post', '/File/Upload', true); xhr.setRequestHeader("Content-Type", "multipart/form-data"); var formData = new FormData(); formData.append("_file", files[i]); xhr.send(files[i]); }

files is an Array()

Then I try to access the post file in C# code, but the value is always null. How can I resolve this issue?

// Method 1, Result: file = null
HttpPostedFileBase file = Request.Files["_file"];

// Method 2, Result: postedFile.Count = 0
HttpFileCollectionBase postedFile = Request.Files;

    

Answer1:

Assuming you have the following form containing the file input field:

<form action="/home/index" method="post" enctype="multipart/form-data" onsubmit="return handleSubmit(this);"> <input type="file" id="_file" name="_file" multiple="multiple" /> <button type="submit">OK</button> </form>

you could try the following function:

function handleSubmit(form) { if (!FormData) { alert('Sorry, your browser doesn\'t support the File API => falling back to normal form submit'); return true; } var fd = new FormData(); var file = document.getElementById('_file'); for (var i = 0; i < file.files.length; i++) { fd.append('_file', file.files[i]); } var xhr = new XMLHttpRequest(); xhr.open(form.method, form.action, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } }; xhr.send(fd); return false; }

Now on the server you should be able to retrieve the file using Request.Files.

Answer2:

You can also use jQuery

you have 2 functions Ajax : http://api.jquery.com/jQuery.ajax/ Load(shortcut, calls ajax) : http://api.jquery.com/load/ Examples : http://www.w3schools.com/jquery/jquery_ajax.asp <strong>Edited</strong> : 2012-10-04 16:31 <strong>Reason</strong> : Got the following Comment : Hm unless I don't understand, I don't want to load informations of the server, I want to get the informations I have in my JS code on my server. I already have the informations to send in the files Array(). – Elfayer

What you do is you make a AJAX call to the server like to an webservice. Here is an example

var value = 1; var handlerUrl = [YOUR WEBSERVICE URL]; //Do the Ajax Call jQuery.ajax({ url: handlerUrl, data: { "params[]": [value] }, type: 'POST', success: function (data) { alert("succes"); }, error: function (jxhr, msg, err) { alert("error"); } });

in the data parameter you give your data. I send it here in the form of an array but you can send it also like 1 parameter. How do you access it in well in my case a generic handler.

//Split the parameters and set in Array of Strings var param = context.Request.Form[0].Split(','); var value = param[0];

Like I said I give it in the form of an array so I only have one parameter and then I split it. But if you would give it like single properties then you could get it like :

context.Request.Form[0] context.Request.Form[1] context.Request.Form[2] context.Request.Form[3] context.Request.Form[4]

Recommend

  • Installing Perl6 and Panda on Ubuntu 15.10. Problems with bootstrap.pl
  • Can my PDF ping my server when it is opened?
  • Using MouseListener to select a range of cells in a grid
  • Getting the scrolling offset when storing coordinates
  • How to explicitly/implicitly implemented interface members in C++/CLI?
  • Bootstrap (v3.3.4) glyphicons not displayed in IE when refresh page (F5)
  • Implementing “partial void” in VB
  • Sending HTML Form Data to Spring REST Web Service
  • Display java JPanel in a JFrame
  • OOP Javascript - Is “get property” method necessary?
  • Android full screen on only one activity?
  • Cancel a live stream “fast motion” catch-up in Flash
  • how to adjust image in a panel in Java swing?
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Retrieving value from sql ExecuteScalar()
  • Encrypt data by using a public key in c# and decrypt data by using a private key in php
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • Accessing IRQ description array within a module and displaying action names
  • Trying to switch camera back to front but getting exception
  • what is the difference between the asp.net mvc application and asp.net web application
  • Rearranging Cells in UITableView Bug & Saving Changes
  • php design question - will a Helper help here?
  • Matrix multiplication with MKL
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • Free memory of cv::Mat loaded using FileStorage API
  • Hits per day in Google Big Query
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • LevelDB C iterator
  • Authorize attributes not working in MVC 4
  • Checking variable from a different class in C#
  • Programmatically clearing map cache
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • Conditional In-Line CSS for IE and Others?