gpt4 book ai didi

c# - MVC HttpPostedFileBase 始终为空

转载 作者:可可西里 更新时间:2023-11-01 08:17:40 25 4
gpt4 key购买 nike

我有这个 Controller ,我想做的是将图像作为 [byte] 发送到 Controller ,这是我的 Controller :

[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>
}

但问题是在我的 Controller 上图像的值总是空的,我似乎无法获得关于 HttpPostedFileBase 的任何信息

最佳答案

您需要使用 multipart/form-data 添加 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 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com