Monday, June 25, 2018

FILE UPLOADING IN ASP.NET MVC USING JQUERY AJAX

<input id="fileupload" class="fileUpload " d  type="file" name="files">
<script>  
$(document).ready(function(){ 
$(document).on('change', '.fileUpload', SaveFileupload); 

 
 function SaveFileupload(e)  {  
  
        // Checking whether FormData is available in browser  
        if (window.FormData !== undefined) {  
  
            var fileUpload = $(this).get(0),
                files = fileUpload.files;  
            if (files[0].size < 20000000) {   
            // Create FormData object  
            var fileData = new FormData();  
      if (files.length > 0) {
            // Looping over all files and add it to FormData object  
            for (var i = 0; i < files.length; i++) {  
                fileData.append(files[i].name, files[i]);  
            }  
              
            // Adding one more key to FormData object  
            fileData.append('username', ‘Naveen’);  
   this.value = '';  //clear file upload control
  }
            $.ajax({  
                url: '/Home/UploadFiles',  
                type: "POST",  
                contentType: false, // Not to set any content header  
                processData: false, // Not to process data  
                data: fileData,  
                success: function (result) {  
                    alert(result);  
                },  
                error: function (err) {  
                    alert(err.statusText);  
                }  
            });  
        } else {  
            alert("FormData is not supported.");  
        }  
         }
    };
 
});  
</script>  
 
In preceding code, first it checks whether windows.FormData is valid in browse. 
Because, using FormData we will send data to server through AJAX request. 
Once FormData object presence checked, it creates a new object. 
Then it fetches files injected in upload control 
and loop over it to add files to FormData object.
 
 
=======================================
Controller (HomeController.cs)
========================================

[HttpPost]  
public ActionResult UploadFiles(string username)  
{  
// Checking no of files injected in Request object  
    if (Request.Files.Count > 0)  
    {  
        try  
        {  
            //  Get all files from Request object  
            HttpFileCollectionBase files = Request.Files;  
            for (int i = 0; i < files.Count; i++)  
            {  
                //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                //string filename = Path.GetFileName(Request.Files[i].FileName);  
  
                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 message that successfully uploaded  
            return Json("File Uploaded Successfully!");  
        }  
        catch (Exception ex)  
        {  
            return Json("Error occurred. Error details: " + ex.Message);  
        }  
    }  
    else  
    {  
        return Json("No files selected.");  
    }  
}  

No comments:

Post a Comment

javascript Filter/index off

 var family = [{"name":"Jack",  "age": 26},               {"name":"Jill",  "age"...