我将图像文件保存在文件夹/ 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();
}
}
FileUpload.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" />
}
答案 0 :(得分:1)
您应该在表格中保存图片名称而不是图片路径。
然后在视图中试试这个:
<img src="~/images/profile/@Model.imageUrl" />
<强> “更新” 强>
见这里:
How to save image in database and display it into Views in MVC?
答案 1 :(得分:0)
像这样保存图像路径:“〜/ images / profile / mypic.jpg”
然后在你看来:
<img src="@Url.Content("~/images/profile/mypic.jpg")" />
或者如果您有Photo类:(将“item”视为您的图片)
<img src="@Url.Content(item.Path)" />
就是这样。
答案 2 :(得分:0)
根据Samiey Mehdi的建议,我在我的代码中完成了这项工作
在控制器中:
newRecord.flName = ImageName;
在视图中:
<img src="~/images/@item.flName" width="100" height="100" />