【问题标题】:How to display saved image in a folder in ASP.net MVC如何在 ASP.net MVC 的文件夹中显示保存的图像
【发布时间】:2013-12-29 10:46:30
【问题描述】:

我将图像文件保存在文件夹 /images/profile 中,我想将图像路径保存在数据库中,但不知道如何在视图中显示图像。我是 MVC 的新手。以下是图片上传的代码。请帮忙。

HomeController.cs

public class HomeController : Controller
    {

        ImageEntities db = new ImageEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
        {
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(
                                       Server.MapPath("~/images/profile"), pic);
                // file is uploaded
                file.SaveAs(path);

            }

    return View("FileUploaded", db.tbl_Image.ToList());

        }

        public ActionResult FileUploaded()
        {
            return View();
        }

    }

文件上传.cshtml

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

FileUploadedView.cshtml

@foreach (var item in Model)
    { 
   <img src="~/images/profile/@item.imagepath" />
    }

【问题讨论】:

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


    【解决方案1】:

    您应该在表格中保存图片名称而不是图片路径

    然后在视图中试试这个:

    <img src="~/images/profile/@Model.imageUrl" />
    

    “更新”

    看这里:

    How to save image in database and display it into Views in MVC?

    【讨论】:

    • 现在只显示图像边框而不是我更新代码的图像。感谢您的建议
    【解决方案2】:

    像这样保存图片路径:“~/images/profile/mypic.jpg”

    然后在你看来:

     <img src="@Url.Content("~/images/profile/mypic.jpg")" />
    

    或者如果您有一个 Photo 类:(将“item”视为您的图像)

     <img src="@Url.Content(item.Path)" />
    

    就是这样。

    【讨论】:

      【解决方案3】:

      根据 Samiey Mehdi 的建议,我在我的代码中这样做是为了让它工作

      在控制器中:

      newRecord.flName = ImageName;

      在视图中:

      &lt;img src="~/images/@item.flName" width="100" height="100" /&gt;

      【讨论】:

        猜你喜欢
        • 2012-03-25
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 1970-01-01
        相关资源
        最近更新 更多