HttpPostedFile in File Upload process is NULL if I use AJAX
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 alwa开发者_JAVA技巧ys NULL on Ajax page.
How can solve this issue along with calling ajax on my page?
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.
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
XHR can not file post.
Asnc file upload use iframe or some library.
精彩评论