File upload with ajax in asp.net mvc

2019-01-28 23:10发布

问题:

I know this has been discussed a lot of times.

I basically want the possibility in my view to update a file. This file has to be mapped to the model the controller expects:

public ActionResult Create(Company company)
{
    //Do something with the received model
}

The model:

public class Company
{
    public int Id { get; set; }
    public HttpPostedFileBase PictureUpload { get; set; }
    ...
}

This is working without any problems. Now I'd like to send my form data, including the file, via AJAX. Therefore I'm using this in my view:

@using (Ajax.BeginForm("Create", "Company", null, new AjaxOptions { HttpMethod = "Post", OnSuccess = "ajaxOnSuccess", OnFailure = "alert('Error message.');" }, new { @class = "ym-form", enctype = "multipart/form-data" }))

This is basically working but the file upload doesn't work (as far as I read ajax doesn't have access to the file so it can't be sent).

I'd like what's the best solution for this problem without having to modify my backend (controller/model).

E. g. I read this article: http://ajeeshms.in/Blog/Article/1/upload-files-using-ajax-in-asp-mvc

It provides two nice possibilities but I'd have to modify the backend because as far as I see the automatically mapping to the HttpPostedFileBase type in my model wouldn't be possible anymore.

I don't mind using any working plugin for my view or using a technique which is supported by new browsers only.

回答1:

Try this code

//Add reference to form.js

<script src="http://malsup.github.com/jquery.form.js"></script>

@using (Html.BeginForm("Create", "Company", FormMethod.Post, new { @enctype ="multipart/form-data",@id="formid" }))
{

}

//Javascript code

<script type="text/javascript">

$('#formid').ajaxForm(function (data) {

});

</script>

This will work as ajax submit.

//You can get more details on AjaxForm here



回答2:

Please try this one @using (Html.BeginForm("Create", "Company", FormMethod.Post, new { id = "ym-form", enctype="multipart/form-data" }))



回答3:

I think you cannot upload files with AJAX. One way to achieve this is to use a hidden iframe. Try this jQuery Form plugin and Telerik file control

Please refer this link also.



回答4:

I have made it based on this answer from Demian Flavius: How to do a ASP.NET MVC Ajax form post with multipart/form-data?

Basically it's the new JavaScript's FormData object that makes it easy for uploading with ajax as in the article your mentioned.