How to Upload file in ASP.NET using jquery ajax
By FoxLearn 2/18/2024 1:17:21 AM 197
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
- Getting Started with ASP.NET Core 3.0
- How to fix 'Authorization in ASP.NET Core' with 401 Unauthorized
- The name 'Session' does not exist in the current context
- How to create a Toast Notifications in ASP.NET Core
- How to fix Font Awesome WebFont woff2 not working BundleConfig
- How to Minify HTML using WebMarkupMin in ASP.NET Core
- How to Minify HTML using WebMarkupMin in ASP.NET MVC
- How to Minify HTML output from ASP.NET MVC
Categories
Popular Posts
How to sign a powershell script
10/03/2024
How to get Credentials in PowerShell?
10/03/2024
How to implement Jint in C#
09/14/2024