简体   繁体   中英

MVC upload and save form image with Ajax

I have a form with 3 inputs (text, image, submit button).

@using (Html.BeginForm("Save", "User", FormMethod.Post, new {Id="Form1", enctype = "multipart/form-data"}))
        {
        <input id="FileUploadInput" name="Image" type="file"/>
        <input id="FirstName"  Name="FirstName">
        <input type="submit" id="inputSubmit" value="Save" />
        }

Now i want to submit this form from javascript with AJAX

$("#inputSubmit").click(function (e) {
            e.preventDefault();
            var form = $("#Form1");
            form.validate();
            if (form.valid()) {
                $.ajax({
                    url: "/User/Save",
                    data: form.serialize(),
                    type: "POST",
                    success: function (data) {
                        if (data === "") {
                            location.reload();
                        }
                        else {
                            $(".content").html(data);
                            $.validator.unobtrusive.parse($(".content"));
                        }
                    }
                });
            }

            return false;
        });

In my controller file i have.

public ActionResult Save(UserProfileSettings settings)
{
  var image = setings.Image
  var name = settings.Firstname
}

My model

public class UserProfileSettings
{
   public string FirstName { get; set; }
   public HttpPostedFileBase Image { get; set; }
}

The problem is that in my controller method i am getting settins.FirstName, but settings.Image is always null. I think, that with this method it is not possible to serialize image file.

尝试使用jquery插件进行多重上传: http ://blueimp.github.io/jQuery-File-Upload/

As Darin Dimitrov suggested before, it's better to use jquery forms plugin . I have already posted this in my another answer here .

Quick Example

View

@using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files"><br>
    <input type="submit" value="Upload File to Server">
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public void YourAction(IEnumerable<HttpPostedFileBase> files)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // TODO: need to define destination
                var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                file.SaveAs(path);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM