How to upload large files using MVC




 This is the third post of file upload in mvc ,first was Upload a File In MVC , second was  Upload Multiple File In MVC  and this is Third "Big File Upload In MVC". In ASP.NET default size of uploading a file is 4MB if  we want to upload a file bigger than 4MB size than we need to have some changes in Web.config file. Lets start

Step1:- For creating a file upload application follow this link Upload a File In MVC  or  Upload Multiple File In MVC    

UploadFile.Cshtml

@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
 
@using (Html.BeginForm("UploadFile""FileUploading"FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <br />
        <input type="file" id="files" name="files" multiple>
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}


FileUploadingController.cs


using System.IO;
using System.Web;
using System.Web.Mvc;
 
namespace FileUpload.Controllers
{
    public class FileUploadingController : Controller
    {
        // GET: FileUploading
 
        public ActionResult UploadFile()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase[] files)
        {
            try
            {
                foreach (HttpPostedFileBase file in files) {
                    if (file.ContentLength > 0)
                    {
                        string fileName = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
                        file.SaveAs(path);
                    }
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }            
        }
    }
}


Step 2:-  Change your system.web section of your Web.config file.

<system.web>

    <compilation debug="true" targetFramework="4.5.2" />

    <httpRuntime targetFramework="4.5.2" maxRequestLength="104857600/>

</system.web>

  

Note:- 
maxRequestLength="104857600"  here size of file in KB


Step3:- Now upload a file bigger than 4 MB . it can be image or video file. 

No comments:

Post a Comment