ASP.NET MVC上传照片 - httpPostedFileBase为null

时间:2016-12-27 15:13:38

标签: javascript asp.net-mvc

编辑:

照片在控制器发布方法中具有空值,尽管我上传了它..

我的模特课是:

class ProductVM{
    public string Name { get; set;}
    public string Color {get; set;}
    public HttpPostedFileBase Photo1 { get; set; }
    }

以下是我使用Razor实现视图的方法:

    @model Project.Models.ProductVM

        @using (Html.BeginForm("AddItem","Item", FormMethod.Post, new { enctype = "multipart/form-data" }))
{


           @Html.AntiForgeryToken()
            @Html.ValidationSummary(true, "", new {@class = "text-danger"})

            @Html.EditorFor(model => model.Name, new {htmlAttributes = new {@class"form-control"}})
            @Html.ValidationMessageFor(model => model.Name)

        // other fields editor's and dropdown's ...


            <div class="col-xs-offset-2 col-xs-8 add-item-rectangle"><input type="file" name="@Model.Photo1" id="file"/></div>
            <div class="col-xs-10 add-item-rectangle"></div>

       <input type="submit" class="btn btn-block add-item-button-text" value="Send"/>

后控制器方法:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddItem(ProductVM product)
        {            
             //**heere when debuging Photo1 is null despite fact that i uploaded photo**

            if (!ModelState.IsValid)
            {
                //... my stuffs
            }

            //..
           return RedirectToAction("Index", "Home");
        }

1 个答案:

答案 0 :(得分:2)

首先,您不能直接发布到字节数组。因此,您需要一个视图模型来表示正在创建/修改的产品。在您的视图模型上,您的文件上传属性应输入为HttpPostedFileBase

public HttpPostedFileBase Image1Upload { get; set; }
public HttpPostedFileBase Image2Upload { get; set; }

您的帖子操作会接受您的视图模型作为参数:

[HttpPost]
public ActionResult CreateProduct(ProductViewModel model)

在此操作中,您将视图模型上的已发布值映射到实体类的相应属性。对于您的上传:

if (model.Image1Upload != null && model.Image1Upload.ContentLength > 0)
{
    using (var ms = new MemoryStream())
    {
        model.Image1Upload.InputStream.CopyTo(ms);
        product.Image1 = ms.ToArray();
    }
}

冲洗并重复其他上传。您可能还想添加一些验证以确保上传的文件实际上是图像,但这样做是为读者留下的练习。

最后,您只需正常保存您的实体。

<强>更新

在更新的代码中,您有以下内容:

<div class="col-xs-offset-2 col-xs-8 add-item-rectangle">
    <input type="file" name="@Model.Photo1" id="file"/>
</div>

首先,@Model.Photo1只输出Model.Photo1的值,即使文件也是如此。相反,Razor只会在属性上调用ToString,您就会获得类似name="System.Web.HttpPostedFileBase"的名称属性。这显然不正确。你需要的是:

<input type="file" name="@Html.NameFor(m => m.Photo1)" id="file" />

或者,更好的是,使用帮助器生成整个输入:

@Html.TextBoxFor(m => m.Photo1, new { type = "file" })