File Upload in ASP.NET MVC in 3 Different Ways

There are a few common functionalities all web applications have; one of the most common functionalities in web applications is File Upload. This is used to transfer data, bulk upload data, and upload photos, videos, etc.

While working on various web applications/products, I mostly encountered mostly 3 different ways to upload a file, especially in ASP.NET MVC. We are going to see it in detail

1. File Control with Html.BeginForm

When we submit the form, we can post our selected file to the server and read it. Below is the code to bind the File control

@Html.TextBoxFor(model => 
       model.DocumentFile, new { 
                type = "file", 
                @id = "documentFile" 

})

And the type of DocumentFile property is as below.

public HttpPostedFileBase DocumentFile { get; set; }

To save this file, we created one folder and added the path of the folder in the config. We are accessing the folder location as below 

var path = ConfigurationManager.AppSettings["CustomerDocuments"].ToString();

Now we need to save the file in the folder and insert the path of the file in the database

if (objGroup.GSTDocumentFile != null)
{
     using (Stream inputStream = objGroup.GSTDocumentFile.InputStream)
     {
         byte[] data;
         using (MemoryStream ms = new MemoryStream())
         {
             inputStream.CopyTo(ms);
             data = ms.ToArray();
         }
         System.IO.File.WriteAllBytes(Path.Combine(ClientFolder, objGroup.GSTDocumentFile.FileName), data);
     }
        objGroup.Document = objGroup.DocumentFile.FileName;
}

2. File upload using AJAX - Base64 as a parameter

When we select a file using file upload on the browser, we need to fire an event to capture the file like below

document.getElementById("uploadfile").addEventListener('change', handleFileSelect, false);

Using this event listener, we execute the function on selection of file and capture the file as below 

function handleFileSelect(evt) {

     const id = evt.currentTarget.id;
     const f = evt.target.files[0];
     const Name = evt.target.files[0].name;
     const reader = new FileReader();

     reader.onload = (function(theFile) {

          return function(e) {

               const binaryData = e.target.result;
               const base64String = window.btoa(binaryData);

               $("#uploadDocBase64").val(base64String);
               $("#uploadFileName").val(Name);

          };

     })(f);

     reader.readAsBinaryString(f);

}

Here we capture the  file as well as the file name, and using AJAX, we can send this file to the server

try {

  const response = await fetch('@Url.Action("FileUpload", "Upload")', {
    method: 'POST',
    body: JSON.stringify({ fileStr: $("#uploadDocBase64").val() }),
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
  });

  const result = await response.json();

  alert('Success');

} catch (error) {

  alert('Failure');
  console.error(error);

}
System.IO.File.WriteAllBytes(path, Convert.FromBase64String(Convert.ToString(fileStr)));

3. File Upload using Fetch with FileData

There is an issue with option no 2. Big files are not getting uploaded as it is going in the parameter. To overcome this, we can add all the parameters and files in fileData and upload a file.

try {

  const fileData = new FormData();

  fileData.append("File", $("#uploadDocBase64").val());

  const response = await fetch('@Url.Action("UpdateStatusAndDiscussion", "Discussion")', {
    method: 'POST',
    body: fileData,
  });

  if (response.ok) {
    alert("Success");
  } else {
    alert("Failure");
  }

} catch (error) {
  console.error(error);
}

Now you can capture the file in the controller

byte[] imageBytes = Convert.FromBase64String(File);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
path = HttpContext.Current.Server.MapPath("~/FileUpload/" + _GroupName + "/" + DoneFileName);
FileStream fileNew = new FileStream(path, FileMode.Create, FileAccess.Write);
ms.WriteTo(fileNew);
fileNew.Close();
ms.Close();

These are the ways to upload files to the server using ASP.NET MVC.

__Happy Coding__


Similar Articles
Logiciel Softtech Pvt. Ltd.
We help you transform your business ideas with custom products, migrate from legacy applications.