MVC使用Ajax上传和保存表单图像

MVC upload and save form image with Ajax

本文关键字:保存 表单 图像 使用 Ajax MVC      更新时间:2023-09-26

我有一个包含3个输入(文本、图像、提交按钮)的表单。

@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" />
        }

现在我想用AJAX 从javascript提交这个表单

$("#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;
        });

在我的控制器文件中,我有。

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

我的型号

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

问题是,在我的控制器方法中,我得到了设置。FirstName,但是设置。图像始终为空。我认为,使用这种方法是不可能序列化图像文件的。

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

正如Darin Dimitrov之前建议的那样,最好使用jquery表单插件。我已经在这里的另一个答案中发布了这一点。

快速示例

查看

@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">
}

控制器

[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);
            }
        }
    }
}