Image upload in mvc with ajax
Loading
Image upload in mvc with ajax
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
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Aug 3, 2023, 4:55 PM EDT
See this article, hope this will help you.
https://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/
Tahir AnsariRank #366 · 6.8K reputationPosted Aug 4, 2023, 2:15 AM EDT
try below sample code:
HTML
$(document).ready(function () { // AJAX request on form submit $("#imageUploadForm").submit(function (e) { e.preventDefault(); // Create a FormData object to send the file var formData = new FormData(); formData.append("imageFile", $("#imageFile")[0].files[0]); // Send the AJAX request $.ajax({ url: "@Url.Action("UploadImage", "Home")", // Replace with your controller action URL type: "POST", data: formData, processData: false, contentType: false, success: function (data) { $("#status").text("Image uploaded successfully!"); }, error: function () { $("#status").text("Error uploading image."); } }); }); });C#
using System.IO; using System.Web; using System.Web.Mvc; public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } // POST: Home/UploadImage [HttpPost] public ActionResult UploadImage(HttpPostedFileBase imageFile) { if (imageFile != null && imageFile.ContentLength > 0) { // Get the filename and extension var fileName = Path.GetFileName(imageFile.FileName); var fileExtension = Path.GetExtension(fileName); // Generate a unique filename (you can use other methods for generating unique names) var uniqueFileName = Guid.NewGuid().ToString() + fileExtension; // Save the file to the server (you can change the path to where you want to store images) var imagePath = Path.Combine(Server.MapPath("~/Uploads/"), uniqueFileName); imageFile.SaveAs(imagePath); // Here, you can perform any additional processing with the image if needed. // Return a success response return Json(new { success = true }); } // If the image is not provided or has no content, return an error response return Json(new { success = false }); } }Amit MohantyRank #112 · 20K reputationPosted Aug 4, 2023, 9:54 AM EDT
Check the article:
https://www.c-sharpcorner.com/article/file-upload-and-download-using-asp-net-mvc-5-for-beginners/
Vishal YelveRank #178 · 13.6K reputationPosted Aug 4, 2023, 10:09 AM EDT
https://www.completecsharptutorial.com/mvc-articles/how-to-upload-and-display-image-using-webgrid-mvc-csharp.php
https://www.compilemode.com/2018/02/upload-images-on-server-folder-in-asp-net-mvc.html
Cr BhargaviRank #420 · 5.9K reputationPosted Aug 4, 2023, 7:28 AM EDT