ASP.net核心未显示上传的图片

时间:2019-05-15 10:47:04

标签: html asp.net-core

我正在尝试加载上传到wwwroot路径的图片。然后,我将文件路径保存到数据库中并进行检索以在我的视图中显示它。

已保存的文件:https://pasteboard.co/IeMBH07.png

ViewBag.Photo中的文件路径:“ C:\ Users \ Me \ source \ repos \ Trinity SOLID \ Trinity \ wwwroot \ Billie.jpg”

视图Img src中的文件路径:C:\ Users \ Me \ source \ repos \ Trinity SOLID \ Trinity \ wwwroot \ Billie.jpg

查看

<h1>match</h1>

<img src="@ViewBag.Photo" alt="Profile" />
<br />

控制器

public ActionResult LoadPotentialMatch()
        {
            string stringID = Request.Cookies["UserID"];
            int ID = Convert.ToInt32(stringID);
            logicmatch.TrulyPotentialMatchesList(ID);

            string value = Convert.ToString(logicmatch.pmatchID);
            SetCookie("pmatchID", value, 10);

            ViewBag.FirstName = logicmatch.FirstName;
            ViewBag.Age = logicmatch.Age;
            ViewBag.Bio = logicmatch.Bio;
            ViewBag.Sex = logicmatch.Sex;
            ViewBag.Photo = logicmatch.Photo;
            return View("match", "Matching");
        }

1 个答案:

答案 0 :(得分:0)

Write your Create POST method as follows:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Item item,IFormFile image)
{
    if (ModelState.IsValid)
    {
        if (image != null && image.Length > 0)
        {
            var fileName = Path.GetFileName(image.FileName);
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\items", fileName);
            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await image.CopyToAsync(fileSteam);
            }
            item.Image = fileName;
        }

        _context.Add(item);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(item);
}

Then for displaying the image in the table:

<td>
    <img class="img-responsive" src="@Url.Content("~/images/items/" + @item.Image)" alt="">
</td>