【问题标题】:MVC 4 ajax form image upload failsMVC 4 ajax 表单图片上传失败
【发布时间】:2014-01-21 19:39:15
【问题描述】:

我正在尝试使用 MVC 4 ajax 表单添加图像,但它总是返回空值。我添加了我的模型、控制器和视图。

我的观点

    @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);
                ...
            }
        }

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

【问题讨论】:

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


【解决方案1】:

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

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

}

【讨论】:

  • 可以去掉方法中的FileImage参数。
  • @Djavier89 已更新!感谢您的观察,刚刚从 koirene 代码中复制并粘贴它,我忘了更新签名!
  • 在更改代码运行良好后,我将 Ajax.BeginForm 转换为 Html.BeginForm。非常感谢。
猜你喜欢
  • 2016-04-11
  • 2010-10-05
  • 2014-12-31
  • 2013-05-14
  • 2016-08-21
  • 2017-02-09
  • 2021-12-22
  • 1970-01-01
  • 2014-10-25
相关资源
最近更新 更多