【问题标题】:Model binding HttpPostedFileBase and then storing the file to datastore模型绑定 HttpPostedFileBase,然后将文件存储到数据存储区
【发布时间】:2010-04-08 15:52:34
【问题描述】:

ASP.NET MVC 似乎正确地在 HTML 表单的文件输入字段和 HttpPostedFileBase 之间自动绑定。另一方面,它不能从文件输入字段绑定到字节数组。我试过了,但它发出了异常——一些关于无法转换为 Base64 的问题。我之前的模型类中只有字节数组属性,因为后来我需要它来将对象序列化为 XML 文件。

现在我想出了这个解决方法,它工作正常,但我不确定这是否可以:

  [DataContract]
     public class Section : BaseContentObject
     {

       ...
      [DataMember]
      public byte[] ImageBytes;

      private HttpPostedFileBase _imageFile;
      public HttpPostedFileBase ImageFile
      {
       get { return _imageFile; }
       set
       {
        _imageFile = value;
        if (value.ContentLength > 0)
        {
         byte[] buffer = new byte[value.ContentLength];
         value.InputStream.Read(buffer, 0, value.ContentLength);
         ImageBytes = buffer;
         ImageType = value.ContentType;
        }
       }
      }

      [DataMember]
      public string ImageType { get; set; }
     }

【问题讨论】:

    标签: asp.net-mvc xml-serialization httppostedfilebase


    【解决方案1】:

    我认为您正在让您的模型与您的控制器紧密连接。通常的做法是:

    public ActionResult AcceptFile(HttpPostedFileBase submittedFile) {
      var bytes = submittedFile.FileContents;
      var model = new DatabaseThing { data = bytes };
      model.SaveToDatabase();
    }
    

    在这种情况下,您的模型不需要知道HttpPostedFileBase,这是一个严格的 ASP.NET 概念。

    如果您需要超出 DefaultModelBinder 提供的复杂绑定(很多),通常的方法是在 Global.asax 中注册专门的 ModelBinders,然后接受您自己的 Model 类作为 Action Method 参数,如下所示:

    Global.asax:

    ModelBinders.Binders.Add(typeof(MyThing), new ThingModelBinder()); 
    

    例如,此 ModelBinder 可以找到随表单发布的任何文件,并将该文件的内容绑定到您的 ThingData 属性。

    在你的控制器中:

    public ActionResult AcceptThing(MyThing thing) {
      thing.Data.SaveToDatabase();
    }
    

    在此 Action Method 中,您的 ThingModelBinder 将处理所有绑定,使其对 Controller 和 Model 都是透明的。

    在这种情况下,无需修改您的实际模型类以了解 ASP.NET 并与之一起工作。毕竟,您的模型类应该代表您的实际数据。

    【讨论】:

    • 你说的有一部分是对的,但我正在努力尝试摆脱 FormCollection 和 HttpPostedFileBase,用强类型模型类替换它们。
    • @mare 我认为您可能会找到更好的方法来做到这一点。我已经更新了我的答案。
    【解决方案2】:

    显然,MVC Futures 2 中发生了巨大的变化(刚刚发现),尤其是在模型绑定器方面。

    例如,我的输入文件绑定到字节数组的问题,现在有一个活页夹:

    • BinaryDataModelBinderProvider – 处理将 base-64 编码输入绑定到 byte[] 和 System.Linq.Data.Binary 模型。

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2019-10-03
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2013-02-08
      相关资源
      最近更新 更多