我有这个控制器,我要做的是将图像作为[字节]发送给控制器,这是我的控制器:

[HttpPost]
public ActionResult AddEquipment(Product product, HttpPostedFileBase image)
 {

            if (image != null)
            {
                product.ImageMimeType = image.ContentType;
                product.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }

            _db.Products.Add(product);
            _db.SaveChanges();

            return View();
 }

在我看来:
@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post)) {

    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Price)
            @Html.ValidationMessageFor(model => model.Price)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Category)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Category)
            @Html.ValidationMessageFor(model => model.Category)
        </div>

        <div>
        <div>IMAGE</div>
        <input type="file" name="image" />

        </div>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

但问题是,在我的控制器上,image的值总是空的,我似乎无法获得关于httppostedfilebase的任何信息。

最佳答案

您需要使用多部分/表单数据添加encType

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

你也可以把它添加到你的模型中,只要它是ViewModel:
public class Product
{
    public Product()
    {
        Files = new List<HttpPostedFileBase>();
    }

    public List<HttpPostedFileBase> Files { get; set; }
    // Rest of model details
}

您可以通过移除不需要的参数来检索文件。
[HttpPost]
public ActionResult AddEquipment(Product product)
 {
    var file = model.Files[0];
    ...
 }

关于c# - MVC HttpPostedFileBase始终为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21998637/

10-11 05:19