3

我正在尝试将图像与其他字段一起上传。一直在关注这里这里的例子

但是,似乎图像对象没有传递给控制器​​,我找不到任何错误。

这是视图:

@model Project.Models.ContentNode
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>News</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>
        @*Image upload field*@
        <div class="editor-field">
            <input type="file" name="file" />
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Body)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.Body)
            @Html.ValidationMessageFor(model => model.Body)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

以下是控制器方法:

public ActionResult Create()
        {
            var model = new ContentNode();
            return View( model );
        }

        [HttpPost]
        public ActionResult Create(ContentNode nyF, HttpPostedFileBase imageData)
        {
            // Get the type of content from DB
            var k = (from ct in _db.ContentTypes
                     where ct.ID == 1
                     select ct).Single();

            var curUser = (from u in _db.Users
                           where u.Username == User.Identity.Name
                           select u).Single();

            nyF.Author = curUser;
            nyF.ContentType = k;
            nyF.dateCreated = DateTime.Now;

            _db.ContentNodes.Add(nyF);
            _db.SaveChanges();

            // Process image
            if ((imageData != null && imageData.ContentLength > 0))
            {
                var fileName = Path.GetFileName(imageData.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                imageData.SaveAs(path);
            }
            else
            {
                return Content("The image object wasn't received");
            }

            return View(nyF);
        }

我一遍又一遍地阅读了整件事,但看不到错误。这里有人愿意指出我做错了什么吗?

4

2 回答 2

5

输入文件的名字需要和action参数匹配

<input type="file" name="file" />

应该

<input type="file" name="imageData" />

或者您更改您的操作参数名称

public ActionResult Create(ContentNode nyF, HttpPostedFileBase file)
于 2012-10-21T20:14:59.487 回答
0

您可以在 post 方法中使用 Request.Files 上传文件。您可以使用以下代码验证上传的文件。

Request.Files[0].ContentLength

于 2013-02-12T06:35:30.703 回答