views:

59

answers:

3

I am using file upload fucntionality 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?

A: 

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 http://stackoverflow.com/questions/254831/asp-net-free-ajax-file-upload-control

Clicktricity
A: 

XHR can not file post.

Asnc file upload use iframe or some library.

takepara
+2  A: 

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