How to Upload file in ASP.NET using jquery ajax
By Tan Lee Published on Feb 18, 2024 538
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 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
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Toolbox Admin Responsive Tailwind CSS Admin Template
Nov 20, 2024
Portal HTML Bootstrap
Nov 13, 2024
Focus Admin Dashboard Template
Nov 18, 2024