【问题标题】:MVC - How do I get a file upload from an html form?MVC - 如何从 html 表单获取文件上传?
【发布时间】:2012-07-23 06:14:09
【问题描述】:

我正在尝试允许用户通过 html 表单上传图像,并且我想将它作为 byte[] 存储在我的模型中。(将存储在 db 中)除非我应该使用其他东西而不是字节[]?

这就是我的表单的样子

@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>

}

这是我的控制器现在的样子

[HttpPost]
    public ActionResult Create(ImageUploadModel model)
    {
           // do stuff

        return View();
    }

这就是我的 ImageUploadModel 的样子

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

当我尝试上传文件时,我收到关于不是有效的 base64 字符串的错误。

在 MVC4 / C# 中将上传的文件作为字节 [] 获取的正确方法是什么

谢谢

【问题讨论】:

    标签: asp.net-mvc file-upload


    【解决方案1】:

    像这样更改您的表单标签(您可以将YourControllerName替换为您的实际控制器名称)

    @using (Html.BeginForm("Create", "YourControllerName", 
                FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
      <input type="file" name="Image" />
      <input type="file" name="Image" id="Image" 
      //your other form elements also
    }
    

    和 更改您的 POST 操作以接受 HttpPostedFileBase 的实例,并且与 input file 元素具有同名

    [HttpPost]
    public ActionResult Create(HttpPostedFileBase Image)
    {
           // do stuff
    
        return View();
    }
    

    【讨论】:

    • 嗯,我刚试过,现在没有错误,但图像只是空。
    • @user1308743:您需要更改表单以接受表单数据。请参阅我的更新答案。
    【解决方案2】:

    您需要将其更改为 HttpPostedFileBase

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 2022-01-19
      • 1970-01-01
      • 2011-11-21
      • 2016-05-01
      • 2010-12-05
      • 2012-04-18
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多