How to Upload file in ASP.NET using jquery ajax
By Tan Lee Published on Feb 18, 2024 724
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
- Implement security headers for an ASP.NET Core
- How to add security headers to an ASP.NET Core Application
- How to Initialize TagHelpers in ASP.NET Core with Shared Data
- Essential Tips for Securing Your ASP.NET Website
- Top Security Best Practices for ASP.NET
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
Categories
Popular Posts
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
Implement security headers for an ASP.NET Core
Jun 24, 2025
Modular Admin Template
Nov 14, 2024
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
Simple Responsive Login Page
Nov 11, 2024