Asp.Net Core 3.1 MVC In my project, the user needs to upload a photo and I want to keep the photo under wwwroot / database. In the database, only the path to the photo is required, but every time my IFromfile object comes as null. Thank you from now
Asked
Active
Viewed 2,171 times
1 Answers
0
You can do it with the following steps.
Create a model
Image
:public class Image { public int Id { get; set; } public string Path { get; set; } }
Create a folder
Images
under yourwwwroot
The index view code:
@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>
Controller:
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(); }
Results:
-
You don't await `CopToAsync()`, and you let users overwrite each other's files by using the provided filename from the upload, instead of generating one serverside. Also, the OP's problem is _"IFromfile object comes as null"_, so the problem is with their client code, which isn't show. – CodeCaster Dec 07 '20 at 09:35
-
I don't know who pity-upvoted this answer, but it is copied from https://stackoverflow.com/a/63822872/, including `fileSrteam` typo and non-unique filename issue, and made worse by removing `await`. – CodeCaster Dec 07 '20 at 09:40