ASP.NET web.config settings for large file uploading

<configuration>
     <appSettings>
	….. 
     </appSettings>
  
     <system.web>
          <compilation debug="true" targetFramework="4.5"/>
          <httpRuntime targetFramework="4.5" 
                       executionTimeout="1000" 
                       maxRequestLength="214748364" 
                       useFullyQualifiedRedirectUrl="false" 
                       minFreeThreads="8" 
                       minLocalRequestFreeThreads="4" 
                       appRequestQueueLimit="100" />
     </system.web>

     <connectionStrings>
        ….
     </connectionStrings>
  
     <system.webServer>
          <validation validateIntegratedModeConfiguration="false" />
          <handlers>
              <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
              <remove name="OPTIONSVerbHandler" />
              <remove name="TRACEVerbHandler" />
              <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"   
                   type="System.Web.Handlers.TransferRequestHandler"  
                   preCondition="integratedMode,runtimeVersionv4.0" />
           </handlers>
           <security>
               <requestFiltering>
                   <requestLimits maxAllowedContentLength="1073741824" />
               </requestFiltering>
           </security>
       </system.webServer>
    
     <runtime>
        ….
     </runtime>
</configuration>


Upload multiple files using AJAX- ASP.NET MVC (multiple file input with same class)

This technique is used to upload multiple files/photos by using multiple file input control (dynamically added), AJAX and ASP.NET-

1. Multiple file input control (with same .class)
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

HTML Part
----------------------------------------

<div class="form-group">
    <input class="multiplephoto" type="file" name="files" multiple />
</div>

<button id="AddMorePhoto">Add more photo </button>
Adding another file input
-----------------------------------------

 $('#AddMorePhoto').on('click', function (e) {
         e.preventDefault();
         $('<div/>').addClass('form-group')
         .html($('<input class="button multiplephoto" type="file" name="files" multiple />'))
         .insertBefore(this);

 });


Submitting the form as FormData via AJAX
-----------------------------------------

var fd = new FormData();

//append some other data to fd. i.e.-
fd.append('PersonName', personName);

var inputs = $('.multiplephoto');
$.each(inputs, function (obj, v) {
    var file = v.files[0];
    fd.append("photos", file);
    //var filename = $(v).attr("data-filename");
});

$.ajax({
    url: "/ControllerName/ActionMethodName",
    type: "POST",
    data: fd,
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    beforeSend: function () {
    },
    success: function (response) {
    },
    error: function (request, status, error) {
    },
    complete: function () {
    }

});
Server-side code
------------------------------------

[HttpPost]
public JsonResult GetPhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    var directory = HttpContext.Server.MapPath("~/Photos");
                
    foreach (var file in photos)
    {
        String fileName = file.FileName;
        string imagePath = Path.Combine(directory, "LoginPhotos", fileName);
        file.SaveAs(imagePath);
    }

    return Json("success");

}

Upload multiple files ASP.NET MVC without AJAX

<form enctype="multipart/form-data" action="/SubmitImage"
         method="post" >
    <input type="file" name="photos" multiple />
    <input type="text" name="caption"/>
    <textarea name="description"></textarea>
    <input type="submit" value="Submit" />
</form>
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitImage(IEnumerable<HttpPostedFileBase> photos,
                                   FormCollection data)
{
    String authString = Request.QueryString["auth"].ToString();
 
    String caption = data["caption"].ToString();
    string description = data["description"].ToString();
 
    if (Request.Files["photos"] != null)
    {
        //The directory where photo will be saved.
        var directory = HttpContext.Server.MapPath("~/Photos");
        foreach (var photo in photos)
        {
            //Get the file name of photo as it being sent.
            //It's required to get the original file extension.
            var photoName = photo.FileName.ToString();
            var extension = Path.GetExtension(photoName).ToLower();
            //Give photo a new name so that it can avoid duplicate name.
            var newName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(directory, newName);
 
            //Check file existence. If exist, try another name.
            if (System.IO.File.Exists(filePath))
            {
               newName = Guid.NewGuid() + extension;
            }
             
            string filePath = Path.Combine(directory, newName);
            photo.SaveAs(filePath); //saving the photo to directory.                    
        }
    }
 
    return RedirectToAction("Index", "UploadImage", new { auth = authString, issubmitted = true });
}

Upload multiple files using AJAX- ASP.NET MVC

This technique is used to upload multiple files/photos by using single file input control, AJAX and ASP.NET-

1. Single file input control
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

<input type="file" id="Photos" multiple />
<!--Save button is disabled to prevent empty file submission-->
<button id="SavePhotos" disabled>Save</button>
<script>
$(function () {
    var fd, saveButton = $("#SavePhotos");
    $("#Photos").change(function (e) {
        fd = new FormData();
        fd.append("id", 1);    
        $.each(e.target.files, function (index, file) {
            fd.append("photos", file);
        });
        saveButton.prop("disabled", false)
    });

    saveButton.click(function () {
        $.ajax({
            url: URL-To-Submit,
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            beforeSend: function () {
            },
            success: function (response) {
                console.log(response);
            },
            error: function (request, status, error) {
            },
            complete: function () {
            }
        });
    });
});
[HttpPost]
public JsonResult SavePhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    try
    {
        var directory = HttpContext.Server.MapPath("~/Photos");

        foreach (var file in photos)
        {
            String fileName = file.FileName;
            String fileExtension = Path.GetExtension(fileName);

            string imagePath = Path.Combine(directory, "HubPhotos", fileName);
            file.SaveAs(imagePath);
        }
    }
    catch (Exception Ex)
    {
        LogException(Ex);
    }

    return Json("success");
}