LIKE US ON FACE BOOK

Wednesday, 8 July 2015

Uploading Files using Ajax in MVC4 using Form object.

Hi Guys ,

If you are looking for a way to upload files in AJAX for in  MVC .
here is simple way, which works like charm :)

please comment if you like it..

//HTML for file upload control
<input type="file" name="myfile" id="pcfile" />


//JS code to access files uploaded and making AJAX call

$(document).on("click", "#btnSubmit", function () {
//here am reading file data from my file upload control
            var file = $('#pcfile').data('ace_input_files');
            if (file.length > 0) {
//check if formdata exists
                if (window.FormData != undefined) {
//create a form object to add files in to form object
                    var fileData = new FormData();
                    for (var i = 0; i < file.length; i++) {
                        fileData.append("file" + i, file[i]);
                        $.ajax({
                            type: "POST",
                            url: '/ControllerName/ActionName' + "?patientID=" + patientID,
                            contentType: false,
                            processData: false,
                            data: fileData,
                            success: function (result) {
                               //success logic
                            },
                            error: function (xhr, status) {
                                console.log(status);
                            }
                        });
                    }
                }
            }
        }
    });

// Action method to read file from HTTP request context object, posting in form object
 [HttpPost]
        public void Uploadfiles(string patientID)
        {
            if (!string.IsNullOrEmpty(patientID))
            {

                //save the uploaded file in path specified in app settings entry
                string fileName = string.Empty;
                String path = string.Empty;
                int pID = 0;
                foreach (string file in Request.Files)
                {
                    var fileContent = Request.Files[file];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        Stream stream = fileContent.InputStream;
                        fileName = User.FirstName + User.LastName + Regex.Replace(DateTime.Now.ToString(), "[^a-zA-Z0-9_]+", "_") + Path.GetExtension(fileContent.FileName);
                        string PatientConsentDirectory = System.Configuration.ConfigurationManager.AppSettings["PatientConsentFilePath"];
                        if (!string.IsNullOrEmpty(PatientConsentDirectory))
                        {
                            bool folderExists = Directory.Exists(Server.MapPath(PatientConsentDirectory));
                            if (!folderExists)
                            {
                                Directory.CreateDirectory(Server.MapPath(PatientConsentDirectory));
                            }
                            path = Path.Combine(Server.MapPath(PatientConsentDirectory), fileName);
                            fileContent.SaveAs(path);
                            stream.Close();
                        }
                    }
                }
            }
        }

Hope this help you, please comment if it helped or if you have any concerns

No comments:

Post a Comment