简体   繁体   中英

ASP.net core not showing uploaded image

Im trying to load in a picture that was uploaded into the wwwroot path. I then save the filepath into the database and retrieve it to show it in my view.

Saved file: https://pasteboard.co/IeMBH07.png

The filepath thats in ViewBag.Photo : "C:\\Users\\Me\\source\\repos\\Trinity SOLID\\Trinity\\wwwroot\\Billie.jpg"

The filepath in the view Img src :C:\\Users\\Me\\source\\repos\\Trinity SOLID\\Trinity\\wwwroot\\Billie.jpg

View

<h1>match</h1>

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

Controller

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");
        }
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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM