2

I am using file upload functionality in my asp.net MVC project. It worked great until I started using some AJAX functionality on my page.

The HttpPostedFile is always NULL on Ajax page.

How can solve this issue along with calling ajax on my page?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
SVI
  • 1,631
  • 3
  • 22
  • 30

3 Answers3

5

Because you cannot upload files using AJAX I would recommend you the excellent jquery form plugin which allows you to ajaxify your forms and supports file uploads. Behind the scenes the plugin generates a hidden iframe to handle the upload and is completely transparent to you:

<form id="myForm" action="/home/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" value="upload" />
</form>

Controller:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    // TODO: handle the file here
    return PartialView("success");
}

And finally ajaxify the form:

$(function() {
    $('#myForm').ajaxForm(function(result) {
        alert('thank you for uploading');
    });
});

Also notice the usage of HttpPostedFileBase instead of HttpPostedFile in the controller action. Being an abstract class this will simplify your unit tests.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Hi can you help me out with a solution to mine also, on http://stackoverflow.com/questions/28695630/how-do-i-upload-an-image-using-jquery-file-input-control-with-my-asp-net-web-ser/28696192#28696192 – floormind Feb 24 '15 at 13:07
0

Its not possible to post a file upload using ajax unless you jump through some hoops - such as posting a sub from from within an IFrame, or by using one of the Flash based solutions. See https://stackoverflow.com/questions/254831/asp-net-free-ajax-file-upload-control

Community
  • 1
  • 1
Clicktricity
  • 4,171
  • 1
  • 23
  • 15
0

XHR can not file post.

Asnc file upload use iframe or some library.

takepara
  • 10,413
  • 3
  • 34
  • 31