MVC HttpPostedFileBase всегда имеет значение null
У меня есть этот контроллер, и я пытаюсь отправить изображение на контроллер в качестве [байта], это мой контроллер:
[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>
}
но проблема в том, что на моем контроллере значение для изображения всегда равно null, я, похоже, не получаю никакой информации о HttpPostedFileBase
Ответы
Ответ 1
Вам нужно добавить encType
с помощью multipart/form-data.
@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
}
Вы можете восстановить файлы, удалив ненужный параметр i.e.
[HttpPost]
public ActionResult AddEquipment(Product product)
{
var file = model.Files[0];
...
}
Ответ 2
Попробуйте сделать это в верхней части метода действия:
[HttpPost]
public ActionResult AddEquipment(Product product, HttpPostedFileBase image)
{
image = image ?? Request.Files["image"];
// the rest of your code
}
И форма должна иметь enctype "multipart/form-data" для загрузки файлов:
@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) {