Asp.Net Core 3.1 MVC 프로젝트에서 사진을 업로드하는 방법은 무엇입니까? [복제]
Dec 07 2020
Asp.Net Core 3.1 MVC 내 프로젝트 에서 사용자는 사진을 업로드해야하며 사진을 wwwroot / database 아래에 보관하고 싶습니다. 데이터베이스에서는 사진의 경로 만 필요하지만 IFromfile 개체가 null로 올 때마다. 지금부터 감사합니다
답변
Yinqiu Dec 07 2020 at 16:21
다음 단계로 수행 할 수 있습니다.
모델 만들기
Image
:public class Image { public int Id { get; set; } public string Path { get; set; } }
Images
아래 에 폴더를 만듭니다.wwwroot
인덱스보기 코드 :
@model Image <form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFile" class="form-control" /> <input type="submit" value="submit" id="sub" /> </form>
제어 장치:
public class HomeController : Controller { private readonly ApplicationDbContext _context; private readonly IWebHostEnvironment _hostingEnvironment; public HomeController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment) { _context = context; _hostingEnvironment = hostingEnvironment; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> IndexAsync(Image image,IFormFile uploadFile) { if (uploadFile != null && uploadFile.Length > 0) { var fileName = Path.GetFileName(uploadFile.FileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName); image.Path = filePath; _context.Images.Add(image); _context.SaveChanges(); using (var fileSrteam = new FileStream(filePath, FileMode.Create)) { await uploadFile.CopyToAsync(fileSrteam); } } return View(); }
결과 :
