In this article i will show you how you can upload a file in asp.net core 6 / MVC without page refresh or ajax file upload using jQuery using c#.net. This article will cove following topics file upload in asp.net core, file upload in asp.net core using ajax,file upload in asp.net mvc core,file/image upload in asp.net core ,how to upload file in asp.net using c#.
Other Related Articles: Upload Multiple File To wwwroot Folder in ASP.NET Core Using C#.Net, Asp.net Core 6 Multiple File Upload, How To Upload Multiple File Asp.net core 6, Upload File To wwwroot Folder in ASP.NET Core Using C#.Net, How To Upload File Asp.net core 6.
Now we will create a new asp.net core application and add a controller class file and add the HttpGet method type.
[HttpGet] public
IActionResult Index() { return View(); } |
Now we will create a folder in our wwwroot folder named as UserFile.
@{ ViewData["Title"] = "Home Page"; } @using
(Html.BeginForm("Index", "Home",
FormMethod.Post, new { @enctype = "multipart/form-data" })) { <span style="font-weight:bold;">Upload File</span> <br /> <div style="color:red;" id="divmessage"></div> <br /> <input type="file" name="formFile" /> <input type="button" value="Submit" /> } |
@{ ViewData["Title"] = "Home Page"; } @using
(Html.BeginForm("Index", "Home",
FormMethod.Post, new { @id = "formuploadfile", @enctype = "multipart/form-data" })) { <span style="font-weight:bold;">Upload File</span> <br /> <div style="color:red;" id="divmessage"></div> <br /> <input type="file" name="files" /> <input type="button" value="Submit" onclick="javascript: UploadFile(this);"/> } <script> var
UploadFile = function (element) { element.value = "Please wait.."; element.disabled = true; var
formData = new FormData(); $("#formuploadfile").find("input[type=file]").each(function (index, field) { const file = field.files; // Looping over all files and add it to FormData
object for (var i = 0; i < file.length; i++) { formData.append("files", file[i]); } }); $.ajax({ url: $("#formuploadfile").attr('action'), type: $("#formuploadfile").attr('method'), contentType: false, //
Not to set any content header processData: false, //
Not to process data data: formData, dataType: 'json', cache: false, success: function (result) { element.value = "Submit"; element.disabled = false; $("#divmessage").html(result.message); $("#formuploadfile")[0].reset(); } }); } </script> |
[HttpPost] public
IActionResult Index(IFormFile files) { try { string
fileName = Path.GetFileName(files.FileName); string uploadpath =
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\UserFiles", fileName); var stream = new FileStream(uploadpath,
FileMode.Create); files.CopyToAsync(stream); return Json(new {
message = "File
uploaded successfully.",
status = 1 }); } catch { return Json(new {
message = "Error
while uploading the files.", status = 0 }); } } |
0 comments:
Please let me know your view