【发布时间】:2019-10-29 02:40:10
【问题描述】:
我正在尝试将图像和视频保存到单独的文件夹而不是数据库中,因为根据我的阅读,最好不要存储在那里。我可以拍摄照片,然后将 URL 字符串保存到数据库中。文件正在保存到正确的位置。
在我拉起视图以显示图像后,它没有显示出来。我可以看到它是一个断开的链接。但不知道如何纠正。
控制器:
[HttpPost]
public IActionResult AddPost(AddPostViewModel addPost, IFormFile file)
{
//Setting the extra data need for the post
addPost.post.DateModified = DateTime.Now;
addPost.post.DatePosted = DateTime.Now;
//Saving the image to a location
SaveImage saveImage = new SaveImage();
Task<String> filePath = saveImage.UploadFile(file);
addPost.post.PostImageVideo = filePath.Result;
//Adding and saving the post to the database and then returning to the admin panel.
_context.Post.Add(addPost.post);
_context.SaveChanges();
ViewBag.SessionUserFirstName = HttpContext.Session.GetString("UserFirstName");
ViewBag.isAdmin = HttpContext.Session.GetString("IsAdmin");
return RedirectToAction("AdminPanel");
}
调用保存图像的方法:
public async Task<String> UploadFile(IFormFile file)
{
var fileName = "";
var filePath = "";
//adding the filepath to the database and saving the path.
if (file != null && file.Length > 0)
{
fileName = Path.GetFileName(file.FileName);
filePath = Path.Combine(Directory.GetCurrentDirectory(),@"~/wwwroot/images/", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return filePath.ToString();
}
然后是从实体中拉取链接或从数据库中拉取链接的视图
@{
ViewData["Title"] = "Post";
}
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h1>@Model.post.Title</h1>
</div>
</div>
<div class="row">
<!--This is grabbing the link for the post.-->
<img src="@Model.post.PostImageVideo" />
<div class="col-md-12">
<p>@Model.post.Body</p>
</div>
</div>
</div>
似乎当我查看链接时,它并没有抓取它所在的 wwwroot 文件夹,它只是直接进入图像。不知道如何更正。
【问题讨论】:
-
您在数据库中存储的图像 uri 的值是多少?在 HTML 中为图像的 uri 呈现什么值?
-
我正在尝试将图片存储在 wwwroot/images 文件夹中。似乎照片在那里。将 combine 语句调整为:lePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/images/", fileName); C:\Users\justi\source\repos\Blog\Blog\wwwroot/images/2years.jpg
标签: c# asp.net-core model-view-controller