Asp.net mvc MVC-如何从html表单上传文件?

Asp.net mvc MVC-如何从html表单上传文件?,asp.net-mvc,file-upload,Asp.net Mvc,File Upload,我试图允许用户通过html表单上传图像,我想在我的模型中将其存储为byte[](将存储在db中),除非我应该使用其他内容而不是byte[]) 这就是我的表格 @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>ImageUploadModel</legend> @Html.DisplayFor(model => model.Image

我试图允许用户通过html表单上传图像,我想在我的模型中将其存储为byte[](将存储在db中),除非我应该使用其他内容而不是byte[])

这就是我的表格

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>ImageUploadModel</legend>

    @Html.DisplayFor(model => model.Image)
   <input type="file" name="Image" id="Image" accept="image/*" />

    @Html.DisplayFor(model => model.Caption)
    @Html.EditorFor(model => model.Caption)
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
public class ImageUploadModel
{
    public Guid UploadedBy { get; set; }

    [Display(Name = "Image")]
    public byte[] Image { get; set; }

    [Display(Name = "Image Caption")]
    public string Caption { get; set; }
}
下面是我的ImageUploadModel的外观

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>ImageUploadModel</legend>

    @Html.DisplayFor(model => model.Image)
   <input type="file" name="Image" id="Image" accept="image/*" />

    @Html.DisplayFor(model => model.Caption)
    @Html.EditorFor(model => model.Caption)
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
public class ImageUploadModel
{
    public Guid UploadedBy { get; set; }

    [Display(Name = "Image")]
    public byte[] Image { get; set; }

    [Display(Name = "Image Caption")]
    public string Caption { get; set; }
}
当我试图上传一个文件时,我得到一个关于不是有效base64string的错误

在MVC4/C中,以字节[]形式获取上传文件的正确方法是什么#


谢谢

您需要将其更改为
HttpPostedFileBase
这样更改您的表单标记(您可以用实际的控制器名称替换
YourControllerName


嗯,我刚刚试过,现在没有错误,但图像为空。@user1308743:您需要更改表单以接受表单数据。请参阅我的最新答案。
[HttpPost]
public ActionResult Create(HttpPostedFileBase Image)
{
       // do stuff

    return View();
}