MVC 4 ajax表单图片上传失败

时间:2014-01-20 17:11:42

标签: asp.net-mvc asp.net-ajax image-upload

我试图通过使用MVC 4 ajax形式添加图像,但它总是返回null值。我添加了我的模型,控制器和视图。

我的观点

    @using (Ajax.BeginForm("Create", "Images", new AjaxOptions { HttpMethod = "Post", OnSuccess = "OnSuccess", OnFailure = "OnFailure", UpdateTargetId = "messageDiv" }, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div class="editor-field">
                    @Html.LabelFor(model => model.Image.Description, new { @class = "control-label" })
                    <div class="controls">
                        @Html.TextBoxFor(model => model.Image.Description)
                    </div>
                    @Html.TextBoxFor(model => model.FileImage, new { type = "file" })
                   @Html.ValidationMessageFor(model => model.FileImage)
                </div>...
    }

我的模特

public class ImageViewModel
    {

        public IList<Image> Images { get; set; }
        public Image Image { get; set; }
        public HttpPostedFileBase FileImage { get; set; }

    }

我的控制器

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ImageViewModel model, HttpPostedFileBase FileImage)
        {
            if (ModelState.IsValid)
            {
                var x = FileImage.FileName;
                var imageUrl = Path.GetFileName(model.FileImage.FileName);
                ...
            }
        }

在此示例中,我无法获取FileName。它总是返回null值。你能帮我解决这个问题吗?我会很开心的。

1 个答案:

答案 0 :(得分:0)

我更希望使用请求读取图像,而不是尝试将其绑定到模型,

public ActionResult Create(ImageViewModel model)
{
    if (Request.Files != null)
    {
        HttpPostedFileBase file = Request.Files[0]; //assuming that's going to be the first file 
        if (file.ContentLength > 0)
        {
           string fileName = Path.GetFileName(file.FileName);
           string directory = Server.MapPath("/"); //change ths to your actual upload folder
           file.SaveAs(Path.Combine(directory, fileName));
        }
    }

}