Обновить изображение с www / Upload / DP / image.png asp.net core 2 - PullRequest
0 голосов
/ 22 сентября 2018

У меня есть код для загрузки изображения, и он работает, как и ожидалось, в моем случае изображение является отображением DP пользователя.

Create.cshtml

<div class="form-group">
                    <label asp-for="DP" class="control-label">Profile Image</label>
                    <input type="file" name="DP" asp-for="DP" class="form-control" />
                    <span asp-validation-for="DP" class="text-danger"></span>
                </div>

Действие контроллера

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Profile profile, IFormFile DP)
        {
            if (ModelState.IsValid)
            {
                var id = _userManager.GetUserName(HttpContext.User);                
                var fileName = Path.Combine(_environment.WebRootPath +"/Upload/DP/", Path.GetFileName(id+".png"));                
                DP.CopyTo(new FileStream(fileName,FileMode.Create));
                //profile.DP = fileName;
                ViewBag.fileName = fileName;              

                var create = new Profile {
                    userName = profile.userName,
                    uId = profile.uId,
                    rId = profile.rId,
                    Mobile = profile.Mobile,
                    Job = profile.Job,
                    City = profile.City,
                    Address = profile.Address,
                    dof = profile.dof,
                    DP = profile.DP = Path.GetFileName(id+".png"),
                    CreatedOn = profile.CreatedOn,
                    Status = profile.Status
                }; 
                    _context.Add(profile);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));                
            }
            ViewData["rId"] = new SelectList(_context.Set<CharityRole>(), "rId", "Name", profile.rId);
            return View(profile);
        }

Вопрос: Как удалить существующее изображение идобавить новый с тем же именем bcz его отображение в профиле пользователя, как:

<img src="@Url.Content("~/Upload/DP/"+ _userManager.GetUserName(User)+".png")">

1 Ответ

0 голосов
/ 24 сентября 2018

В вашем сообщении есть две проблемы.

  • Вам необходимо использовать Using для FileStream, иначе файловый поток не будет удален.

            using (var fileStream = new FileStream(fileName, FileMode.Create))
            {
                await DP.CopyToAsync(fileStream);
            }
    
  • Вам нужно передать create вместо profile на _context.Add.

Вот полный демонстрационный код:

        public async Task<IActionResult> Create(Profile profile, IFormFile DP)
    {
        if (ModelState.IsValid)
        {
            var id = _userManager.GetUserName(HttpContext.User);
            var fileName = Path.Combine(_environment.WebRootPath + "/Upload/DP/", Path.GetFileName(id + ".png"));
            using (var fileStream = new FileStream(fileName, FileMode.Create))
            {
                await DP.CopyToAsync(fileStream);
            }
            var create = new Profile
            {
                UserName = profile.UserName,                    
                DP = Path.GetFileName(id + ".png")                    
            };
            _context.Add(create);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(profile);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...