在View中显示文件路径中的图像

时间:2018-03-02 01:33:43

标签: c# asp.net-mvc razor

如何从数据库中检索的位置显示图像?

我检索了一个位置列表(物理路径),并尝试了下面的方法,没有显示图像。我使用SQL来存储文件路径(例如c:\ 123.jpg“)。

@model FoodSnap.ViewModels.FoodSnapViewModel
@{
ViewBag.Title = "Create";
}

<h2>Daily Review</h2>

@using (Html.BeginForm("Create", "FoodSnap"))
{   
    <div class="container">
        <div class="row">
            <div class="col-xs-2">
                <img src="@Html.Raw(Model.ImageLocations[0])" alt="Image1" />
                <img src="@Url.Content(Model.ImageLocations[0])" alt="Image2" />
                <img src="@Model.ImageLocations[0]" alt="Image3" />
               style="width:150px;height:150px" />
            </div>
        </div>
    </div>
}

我的控制器如下:

public ActionResult Create()
    {
        DateTime d1 = DateTime.Now.AddDays(-2);
        DateTime d2 = DateTime.Now.AddDays(1);

        string fd1 = d1.ToString("yyyy-MM-dd");
        string ld1 = d2.ToString("yyyy-MM-dd");

        DateTime StartDate = Convert.ToDateTime(fd1);
        DateTime EndDate = Convert.ToDateTime(ld1);           

        FoodSnapViewModel model = new FoodSnapViewModel
        {
           ImageLocations = new List<string>(from x in db.FoodType.OrderBy(x => x.fldTimeStamp).ToList() where x.fldUserId == User.Identity.GetUserId() && x.fldTimeStamp >= StartDate && x.fldTimeStamp < EndDate select x.fldImageId)
        };

        return View(model);          
    }

我当然是将数据传递给View,但我无法使用路径显示图像。我没有在数据库中使用字节流,因为我不想用它来存储图像。

任何指针都会受到赞赏......

1 个答案:

答案 0 :(得分:0)

我使用了@ADyson方法并使用了base64方法,它正在运行。

 public string GetImage(string file)
    {
        string imgPath = Server.MapPath("~/Content/UserImages/Originals/" + file);
        byte[] byteData = System.IO.File.ReadAllBytes(imgPath);
        string imreBase64Data = Convert.ToBase64String(byteData);
        string imgDataURL = string.Format("data:image/jpg;base64,{0}", imreBase64Data);

        return imgDataURL;
    }