Thursday, 13 January 2022

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery

1/13/2022 - By Pranav Singh 0

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#.NetAsp.net Core 6 Multiple File Upload, How To Upload Multiple File Asp.net core 6Upload 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.


folder in wwwroot

After this we will create a view and add the below code into it.

@{

    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" />

}


Now we will write out jQuery code to perform the operation.

@{

    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>


In above code i have defined a javascript function named as UploadFile. In this function just check the highlighted part of the code. in this the file name is same as the input control file name. If it differ you will receive null at controller end. 

One more thing which needs to taken care enctype. You must specify in your form tag. Now call the function on click of the button.  Now we will write the code HttpPost. 

[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 });

            }

        }


In above code check the IFormfile parameter. It's name is same as the input file control name.  Now we have done run the code and check the output.

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery

Now select the file and click on "Submit" button.

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery

Now check the controller code.

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery


Now final output.

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery


Here we have got success message.  Now we will check the folder for output.

ASP.NET Core 6 : Ajax Upload File( Without Page Refresh) To wwwroot Folder in Using C#.Net , jQuery

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top