How to do javascript file upload?


Hello, I am working on a web-application in which I would to upload file using javascript, as soon as someone select's the file using HTML file input, so what should be the code for uploading file using javascript?

Although I need only front-end code/tutorial link etc, but if possible i would like to know C# code to get it in MVC Controller also, thanks.


Asked by:- jon
2
: 6746 At:- 5/30/2018 3:32:10 PM
Javascript File upload C# ASP.NET MVC







2 Answers
profileImage Answered by:- manish

You can easily upload file on server using javascript, suppose, your HTML is like below

<input type="file" id="UploadFile" />

and now you want to upload file on changing file, you can call jQuery function on('change') and then implement javascript code to upload it

 //For Uploadingfile on file input change
            $(document).on('change', "#UploadFile", function () {
               //get files
                var fileInput = document.getElementById('UploadFile');
                //select only first file
                var file = fileInput.files[0];
               
                //create form data and append file in it
                var formData = new FormData();
                formData.append('file', file);


                //create variable for starting new XMLHttprequest
                var xhr = new XMLHttpRequest();
               
                xhr.onreadystatechange = function () {
                    //this will be called upon successful execution of file upload
                    if (this.readyState == 4 && this.status == 200) {
                        //do something here
                        console.log(xhr.responseText);
                       
                    }
                };
                var Id = $("#Id", "#FormAjax").val();
               
                // Add any event handlers here...
               //sending POST request to server
                xhr.open('POST', '/URLToUpload', true);
                xhr.send(formData);

                return false; // To avoid actual submission of the form, if needed

            })

Your front end code to send file to server using javascript is done.

[Continue reading if you are C# MVC developer]On the back-end, you can implement C# code in controller like below

       [HttpPost]
      
        public ActionResult UploadFile(int id)
        {
            var FileURL = "";
           
            // Get files
            HttpFileCollectionBase files = Request.Files;
            //loop through all the formData files
            for (int i = 0; i < files.Count; i++)
            {
               
               
                HttpPostedFileBase file = files[i];
                string fname;

                // Checking for Internet Explorer  
                if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                }

                // Get the complete folder path and store the file inside it.  
                fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);

             

                file.SaveAs(fname);
            }
            // Returns the file URL that is successfully uploaded  
            return Json(FileURL);
            
        }

I have tested this code for my own project locally and it is working.

There is also another article related to File uploading using jQuery Ajax in MVC C#, you can take a look if needed.

4
At:- 5/31/2018 12:55:23 PM Updated at:- 12/24/2022 7:11:17 AM
perfect answer, thank you 0
By : jon - at :- 6/5/2018 11:42:45 AM


profileImage Answered by:- vikas_jk

Considering you have below HTML

 <input id="file" type="file" />

Javascript to file upload will be

let photo = document.getElementById("file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

then on Server side, you need to get create a httppost request and get form values.

"photo" = name of the file contents on server side.

3
At:- 9/27/2021 11:40:08 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use