How to Upload file in ASP.NET using jquery ajax
By FoxLearn 2/18/2024 1:17:21 AM 290
This tutorial shows you how to upload a file in ASP.NET MVC using Ajax and javascript without page refresh.
You can add a simple html layout that allows you to select a file from your hard disk, then click the upload button to upload your file to the web server.
<input type="file" id="fileUpload" class="form-control" /> <br /> <button id="upload" class="btn btn-primary">Upload</button>
Add a javascript at the bottom page as the following
<script> $("#upload").click(function () { if (window.FormData == undefined) alert("Error: FormData is undefined"); else { var fileUpload = $("#fileUpload").get(0); var files = fileUpload.files; var fileData = new FormData(); fileData.append(files[0].name, files[0]); $.ajax({ url: '/home/fileupload', type: 'post', datatype: 'json', contentType: false, processData: false, async: false, data: fileData, success: function (response) { alert(response); } }); } }); </script>
Next, Create a upload action in your Home controller
public JsonResult FileUpload() { // check your user selected a file to upload if (Request.Files.Count > 0) { try { HttpFileCollectionBase files = Request.Files; HttpPostedFileBase file = files[0]; string fileName = file.FileName; // create the uploads folder if it doesn't exist Directory.CreateDirectory(Server.MapPath("~/uploads/")); string path = Path.Combine(Server.MapPath("~/uploads/"), fileName); // save the file file.SaveAs(path); return Json("Your file has been successfully uploaded."); } catch (Exception e) { return Json("error" + e.Message); } } return Json("Please select a file to upload !"); }
As you can see, we will call the fileupload action by using ajax
- How to use CORS in ASP.NET Core
- How to Send Emails in ASP.NET Core
- How to Run Background Tasks in ASP.NET Core with Hosted Services
- Implementing Scheduled Background Tasks in ASP.NET Core with IHostedService
- Creating an Web API in ASP.NET Core
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- 10 Common Mistakes ASP.NET Developers Should Avoid
- How to Upload Files Using C# ASP.NET FileUpload Control
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024