如何使用MVC 4显示图像?

时间:2013-11-04 15:09:11

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

我是mvc的新手,我是mvc4应用程序,我想显示已经上传到服务器路径的机器图片

public partial class Picture
{
    public Picture()
    {
        this.Approvments = new HashSet<Approvment>();
    }

    public int PicId { get; set; }
    public string PicPath { get; set; }
    public Nullable<bool> Status { get; set; }
    public Nullable<System.DateTime> PickDate { get; set; }
    public Nullable<int> UserId { get; set; }
    public Nullable<int> ApproveId { get; set; }
    public Nullable<int> MacId { get; set; }

    public virtual ICollection<Approvment> Approvments { get; set; }
    public virtual Machine Machine { get; set; }
    public virtual User User { get; set; }
}

}

这是我的控制器上传到特定路径

 public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                string name = Guid.NewGuid().ToString().Replace("-", "");
                var fileName = Path.GetFileName(file.FileName+name);
                var path = Path.Combine(Server.MapPath("~/App_Data/upload"), fileName);
                file.SaveAs(path);
            }
        }
        return RedirectToAction("Index");
    }

我不知道去哪里只显示图像??

2 个答案:

答案 0 :(得分:1)

在www根目录中创建一个文件夹,例如将您的图像设置为“MyImages”。如果将someImage.png保存到此目录中,请将此图像的uri(www.yourdomainname / MyImages / someImage.png)打印到模型中,并在视图中使用它。

将图片网址列表传递给视图,如下所示

List<string> urlList = new List<string>();
urlList.Add("www.mydomainname.com/MyImages/image1.png");
urlList.Add("www.mydomainname.com/MyImages/image2.png");
urlList.Add("www.mydomainname.com/MyImages/image3.png");

return RedirectToAction("Index",urlList); //pass model into view

在视图方面使用像这样的模型

@model List<string>
@foreach (string url in Model)
{
    <img src="@url"/>
}

答案 1 :(得分:1)

Controller

    public ActionResult DisplayPic()
    {
      Picture picture = new Picture();
      picture.PicPath = GetImagePath();  //Logic to get the image path as string
      return View(picture);
     }

View

@model YourNameSpace.Model.Picture

<img src= "@Url.Content(Model.PicPath)" alt="Image"/>

没有检查代码,但这应该做..!如果有帮助请告诉我