Configure ASP.NET MVC To Accept Large File Uploading

///
///In Web.config
///

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

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

    <connectionStrings>
        ....
    </connectionStrings> 
</configuration>
///
/// In Controller
///

[ValidateInput(false)]
[HttpPost]
public JsonResult UploadAudio()
{
    try
    {
        foreach (string f in Request.Files.AllKeys)
        {
            var file = Request.Files[f];

            var path = HttpContext.Server.MapPath("~/Voices");
            if (!System.IO.File.Exists(System.IO.Path.Combine(path, file.FileName)))
            {
                file.SaveAs(System.IO.Path.Combine(path, file.FileName));
            }
        }

        return Json("success");
    }
    catch (Exception Ex)
    {
        return Json("Server says:" + Ex.Message, JsonRequestBehavior.AllowGet);
    }
}
Advertisements

Client-Server File Handling Technique

//Server side
[ValidateInput(false)]
[HttpPost]
public JsonResult ReceiveAudio()
{
    try
    {
        foreach (string f in Request.Files.AllKeys)
        {
            var file = Request.Files[f];
            string fileName = file.FileName.ToString();
        }

        return Json("success");
    }
    catch (Exception Ex)
    {

    }
}

Upload file from WinForm application to server

using BizArk.Core.Web; // http://bizark.codeplex.com/
var response = WebHelper.MakeRequest
                  ("http://Domain.com/Home/ReceiveAudio/",
                    new
                       {
                          wavFile = new FileInfo(e.FullPath)
                          //Test = "Hello",
                          //File1 = new UploadFile(@"text\plain", "file1.txt", 
                                   new MemoryStream(Encoding.UTF8.GetBytes("Hello "))),
                          //File2 = new FileInfo("MyFile.txt")
                        });

var result = response.ResultToString();

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

ASP.NET Maximum request length exceeded

//I modified <system.web>..</system.web>  and <system.webServer>..</system.webServer>. The problem got solved.
<system.web>
    //I added this maxRequestLength="100000" in system.web
    <httpRuntime targetFramework="4.5" maxRequestLength="100000"/>
</system.web>
 
<system.webServer>
    //I also added the block <security>..</security>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
</system.webServer>
  
  
//There are some other suggestions from various blogs/forums
<system.web>
  <httpRuntime executionTimeout="100000" maxRequestLength="214748364" />
</system.web>

Subitted file handling technique in server-side ASP.NET (along with other data) in Non-AJAX way


//--> Non-ajax way --------------------------------
  //HTML
          <form method="post" action="~/Admin/Content/SubmitFile" enctype="multipart/form-data">
                <select name="course" id="course">...</select>
                <input type="text" name="lesson" id="lesson" />
                <input type="file" name="myfile" />
                <input type="submit" value="submit" />
          </form>
  
  //Server-side
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult SubmitFile(FormCollection data)
        {
             String lessonName = data["lessonName"].ToString();
             
            //--> Option-A
              var fileName = Request.Files["filea"].FileName.ToString();
              var fileExtension = Path.GetExtension(fileName);
              var mainSavingDirectory = HttpContext.Server.MapPath("~/Photos");
              string fileSavingPath = Path.Combine(mainSavingDirectory, "Content", "Video", fileName);
              var file = Request.Files["myfile"];
              file.SaveAs(fileSavingPath);
            //<-- Option-A   
            
            //--> Option-B
              Byte[] submittedFile;
              if (Request.Files["myfile"] != null)
              {
                String fileName = "AnyName.ext";
                var mainSavingDirectory = HttpContext.Server.MapPath("~/Photos");
                string fileSavingPath = Path.Combine(mainSavingDirectory, "Content", "Video", fileName);
 
                using (var binaryReader = new BinaryReader(Request.Files["myfile"].InputStream))
                {
                    submittedFile = binaryReader.ReadBytes(Request.Files["myfile"].ContentLength);
                }
                FileStream fs = new FileStream(fileSavingPath, FileMode.CreateNew);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(submittedFile);
                bw.Close();
              }
        }
//<-- Non-ajax way --------------------------------