Asp.Net Core 3.1 MVC Wie lade ich Fotos in das Projekt hoch? [Duplikat]
Dec 07 2020
Asp.Net Core 3.1 MVC In meinem Projekt muss der Benutzer ein Foto hochladen und ich möchte das Foto unter wwwroot / database behalten. In der Datenbank ist nur der Pfad zum Foto erforderlich, aber jedes Mal, wenn mein IFromfile-Objekt als null angezeigt wird. Vielen Dank von jetzt an
Antworten
Yinqiu Dec 07 2020 at 16:21
Sie können dies mit den folgenden Schritten tun.
Erstellen Sie ein Modell
Image
:public class Image { public int Id { get; set; } public string Path { get; set; } }
Erstellen Sie einen Ordner
Images
unter Ihremwwwroot
Der Indexansichtscode:
@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>
Regler:
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(); }
Ergebnisse:
