How can i user IFormFile to store and preview the image on application
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tuhin PaulRank #7 · 71.9K reputationPosted May 4, 2023, 8:20 AM EDT
[HttpPost] public async Task UploadImage(IFormFile imageFile) { if (imageFile != null && imageFile.Length > 0) { // Generate a unique file name to prevent overwriting string fileName = Guid.NewGuid().ToString() + Path.GetExtension(imageFile.FileName); // Create a path to store the file string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "images", fileName); // Save the file using (var fileStream = new FileStream(filePath, FileMode.Create)) { await imageFile.CopyToAsync(fileStream); } // Store the file name in TempData to display it on the preview page TempData["ImageFileName"] = fileName; return RedirectToAction("PreviewImage"); } return View(); }Tuhin PaulRank #7 · 71.9K reputationPosted May 4, 2023, 8:20 AM EDT
public IActionResult PreviewImage() { string fileName = TempData["ImageFileName"]?.ToString(); if (string.IsNullOrEmpty(fileName)) { return RedirectToAction("UploadImage"); } string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "images", fileName); return View((object)filePath); }