编辑:
尽管我上传了照片,但它在 Controller post 方法中具有空值。
我的模型类是:
class ProductVM{
public string Name { get; set;}
public string Color {get; set;}
public HttpPostedFileBase Photo1 { get; set; }
}
以下是我如何使用 Razor 实现 View :
@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"/>
后置 Controller 方法:
[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");
}
最佳答案
首先,您不能直接发布到字节数组。因此,您需要一个 View 模型来表示正在创建/修改的产品。在您的 View 模型上,您的文件上传属性应键入 HttpPostedFileBase
:
public HttpPostedFileBase Image1Upload { get; set; }
public HttpPostedFileBase Image2Upload { get; set; }
您的后操作将接受您的 View 模型作为参数:
[HttpPost]
public ActionResult CreateProduct(ProductViewModel model)
在此操作中,您将把 View 模型上发布的值映射到实体类上的相应属性。对于您的上传:
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" })
关于javascript - ASP.NET MVC 上传照片 - httpPostedFileBase 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347644/