ASP.NET MVC:从Db中将存储的图像视为byte []

时间:2016-12-18 09:54:57

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我已经将图像存储在一个表格的列中以及其他信息,但是我在检索有关帖子的全部信息时显示图像。 我正在被打破img'图标。

型号:

poll()

创建动作:

public class Event
{
[Key]
public int Id { get; set; }
public string EventName { get; set; }
public byte[] EventPhoto { get; set; }
}

输入视图:

    [Authorize]
    [HttpPost]
    public ActionResult Create(Event events, [Bind(Exclude = "EventPhoto")]EventController model)
    {
    if (ModelState.IsValid)
    {
        using (var database = new EventSpotDbContext())
        {
            byte[] imageData = null;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase poImgFile = Request.Files["EventPhoto"];

                using (var binary = new BinaryReader(poImgFile.InputStream))
                {
                    imageData = binary.ReadBytes(poImgFile.ContentLength);
                }
            }
            events.EventPhoto = imageData;
            database.Events.Add(events);
            database.SaveChanges();
            return RedirectToAction("Main");
        }
    }
return View(events);
}

显示操作:

     @Html.LabelFor(m => m.EventPhoto)
   <input type="file" name="Event" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />

显示视图:

  public ActionResult DisplayImg(Event events)
    {
        var bdEvents = HttpContext.GetOwinContext().Get<EventSpotDbContext>();
        var userImage = bdEvents.Users.Where(x => x.Id == (events.Id).ToString()).FirstOrDefault();
        return new FileContentResult(events.EventPhoto, "image/jpg");
    }

解决我的问题?

2 个答案:

答案 0 :(得分:0)

一方面,DisplayImg操作需要Event参数,因此请尝试发送一个参数。你现在正在发送一个字符串。试试这个:

<img src="@Url.Action("DisplayImg", Model)" />

更好的解决方案是通过发送Model.Id并接收您用于查找的int来传递事件条目的ID。

但是,您编写的DisplayImg函数也已关闭,您使用参数的Id属性查找图像,然后返回EventPhoto字段代替。您应该返回您查找的图像。

在没有实际请求/响应数据转储的情况下,我可以告诉您。 &#34;图像破碎&#34;与牛奶一样有用的调试辅助工具。不要在你的电脑上扔牛奶来修复虫子。

答案 1 :(得分:0)

您的<file>属性名为Event,但您尝试使用Request.Files["EventPhoto"]访问该文件。

您应该在视图中使用您为其指定的名称:

Request.Files["Event"]
相关问题