HttpPostedFile in File Upload process is NULL if I

2019-05-25 10:32发布

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?

3条回答
The star\"
2楼-- · 2019-05-25 11:14

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

查看更多
迷人小祖宗
3楼-- · 2019-05-25 11:16

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-25 11:29

XHR can not file post.

Asnc file upload use iframe or some library.

查看更多
登录 后发表回答