【问题标题】:Difficulties to send File to view using FileContentResult action method使用 FileContentResult 操作方法发送文件以查看的困难
【发布时间】:2010-07-06 21:36:09
【问题描述】:

我需要以这种方式在视图上显示图像

<img src = <% = Url.Action("GetImage", "Home", new { productID })%>

这是应该提供数据的操作

public FileContentResult GetImage(int ID)
{
  var img = db.Images.Where(p => p.ID == ID).First();
  return File(img.ImageData, img.ImageMimeType);
}

这个例子来自 Pro ASPNET.NET MVC (Steven Sanderson/APress)。我收到以下错误:System.Web.Mvc.Controller.File(string, string) 的最佳重载方法匹配有一些无效参数。 无法从 System.Data 转换。 Linq.Binary 转字符串。

然而,智能感知告诉我有一个重载方法(byte[] filecontents, string fileType)。但是,当我编写上面的代码时,我得到了错误。我错过了什么吗?

编辑

感谢您的回答。我在上传图像文件时遇到了类似的问题。这是我的操作方法

public ActionResult AddImage(HttpPostedFileBase image)
{
  if(image != null)
    {
      var img = new Image();//This Image class has been 
                            //created by the DataContext
      img.ImageMimeType = image.ImageMimeType
      img.ImageData = new byte[image.ContentLength];
      image.InputStream.Read(img.ImageData, 0, image.ContentLength);
    } 
}

最后一行出现错误“image.InputStream.Read(myImage.ImageData, 0, image.ContentLength);说它不能转换 System.Data .Linq.Binary to Byte[]

我所做的是 (i) 创建一个名为 ImageDataClass 的新类,(ii) 对该类执行上述操作,(iii) 执行从 ImageDataClass 到 Image 的显式转换,以及(iv) 使用 Linq 保存到数据库。

我认为它不应该那么复杂。对于另一种情况,是否有任何方法可以仅使用 ToArray 之类的扩展方法使其工作?

感谢您的帮助

【问题讨论】:

    标签: asp.net-mvc file-io


    【解决方案1】:

    File() 有一个使用字节数组的重载,但您试图传入System.Data.Linq.Binary 的类型,而不是字节数组。不过Binary上有一个方法可以转换成字节数组。

    试试这个:

    public FileContentResult GetImage(int ID)
    {
      var img = db.Images.Where(p => p.ID == ID).First();
      return File(img.ImageData.ToArray(), img.ImageMimeType);
    }
    

    编译错误提到“字符串”的原因纯粹是因为它无法确定您尝试的重载,所以它只是选择一个,在这种情况下是字符串,然后报告类型转换错误。

    [编辑:响应 OP 编辑​​]

    你应该可以试试这样的:

    public ActionResult AddImage(HttpPostedFileBase image)
    {
      if(image != null)
        {
          var img = new Image();//This Image class has been 
                                //created by the DataContext
          img.ImageMimeType = image.ImageMimeType
          var imageData = new byte[image.ContentLength];
          image.InputStream.Read(imageData, 0, image.ContentLength);
          img.ImageData = new System.Data.Linq.Binary(imageData);
        } 
    }
    

    请记住,尽管System.Data.Linq.Binary 可能只是下面的一个字节数组,或者至少旨在表示字节数据,但它本身并不是byte[] 类型;你仍然需要转换(与System.IO.MemoryStream类似的情况)

    【讨论】:

    • 感谢您的回答,它成功了。我确实有其他类似的问题,所以请阅读我的帖子的编辑。
    • 在上面的示例中,“Image”的完全限定类型名称是什么?只是想仔细看看可用的方法和属性。
    • 我的数据库中有一个名为 Images 的表。在我将它拖放到 LinqToSQL 编辑器上后,它会失去“s”并变成 Image。所以,Image 是由 DataContext 创建的类。
    • ok - 所以 ImageMimeType 和 ImageData 都是数据库中的列。第一个,大概是一个字符串,第二个是一个二进制字段......等我快速思考一下:)
    • 我试试看结果告诉你。
    猜你喜欢
    • 2019-05-20
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多