



Buffering Technique In File Upload:

The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.

Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.

Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.

If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading.

Create The .NET Core MVC Project:

IFormFile:

Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files from the client, then the entire file gets loaded into the IFormFile. This IFormFile type can be used as a model binding property in the MVC action methods. In simple terminology, IFormFile is a represents a file sent with the HttpRequest to the server. The following are a few IFormFile interface members and properties:



ContentDisposition property in IFormFile represents the header that gives information about the field (about the file uploading).

The example below shows the ContentDisposition header with value on the requesting server.

Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" used for file upload with buffered technique. On uploading files from the client, then the entire file gets loaded into the IFormFile. This IFormFile type can be used as a model binding property in the MVC action methods. In simple terminology, IFormFile is a represents a file sent with the HttpRequest to the server. The following are a few IFormFile interface members and properties:property in IFormFile represents the header that gives information about the field (about the file uploading).The example below shows the ContentDisposition header with value on the requesting server.

multipart/form-data:

multipart/form-data is one of the content-type headers for the post method. multi-part/form-data used mainly in file upload post data. Having this content-type means each value is sent as a block of data and each block is separated by the delimiter "boundary".





For example, a form submitting with some information and an image to the server and form furnished with encrypt attribute with value multipart/form-data then post request information looks as below

Host: mywebsite.com Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="mypic.jpg"

Create A MVC Model:

File upload using IFormFile type can be done with .NET Core MVC model binding. So file data can be received in the model property of type IFormFile.

Using IFrameFile type means using Buffer technique.

using Microsoft.AspNetCore.Http; namespace SingleFileUpload.MvcApp.Models { public class FileUpload { public IFormFile FormFile { get; set; } } }

Update Index.cshtml File With File Upload Html:

Now update the index.cshtml page with following Html.

Views/Home/index.cshtml:

@model SingleFileUpload.MvcApp.Models.FileUpload <div class="text-center"> <form enctype="multipart/form-data" method="POST"> <dl> <dt> <label asp-for="@Model.FormFile"> Upload Your File </label> </dt> <dd> <input asp-for="@Model.FormFile" type="file" /> </dd> </dl> </form> </div>

Here on form tag, we can observe encrypt Html attribute.

This encrypt attribute specifies how the form data to be encoded while submitting data to the server.

The values accepted by the encrypted attribute are 'application/x-www-form-urlencoded', 'multipart/form-data' and 'text/plain'.

For file uploading the encrypt attribute will set with 'multipart/form-data'.

The input tag type was assigned with 'file' value which represents for upload file. By assigning 'file' value to the input tag browser automatically renders file upload button and on clicking that button it opens file explorer to select the file to upload.

File Upload Action Method:

Now create a new folder in wwwroot folder in the application tree directory to store images.

Now to access the physical path of wwwroot folder while saving image .NET Core provides an interface 'Microsoft.AspNetCore.Hosting.IWebHostEnvironment'. So inject this 'IWebHostEnvironment' in the controller as below.

Controllers/HomeController.cs:

using Microsoft.AspNetCore.Hosting; public class HomeController : Controller { private readonly IWebHostEnvironment _env; private readonly ILogger<HomeController> _logger; public HomeController( ILogger<HomeController> logger, IWebHostEnvironment env) { _logger = logger; _env = env; } // existing code hidden for display purpose }

[HttpPost] public IActionResult UploadFile(FileUpload fileUpload) { if (fileUpload.FormFile != null) { string filePath = $"{_env.WebRootPath}/images/{fileUpload.FormFile.FileName}"; using (var stream = System.IO.File.Create(filePath)) { fileUpload.FormFile.CopyTo(stream); } } return Redirect("/"); }

Here we can observe 'FileUpload' is a model class that has the property of type IFormFile which holds uploaded file.

Using the IWebHostEnvironment interface we are fetching the wwwroot folder path to save the uploaded image.

The file we are saving with the name provided by the user client.

'System.Io.File.Create' either creates or overrides the file to the destination path provided as its input parameter.

Using IFormFile.Copy method which takes the stream as input, it will copy the content it contains in IFormFile to the destination specified in its input stream.

Update Form Html Tag In Index.cshtml:

Now update the Form Html tag with submission path using razor syntax to specify the controller and action method name.

<form asp-controller="Home" asp-action="UploadFile" enctype="multipart/form-data" method="POST"> <!-- code hidden for display purpose --> <button type="submit" class="btn btn-primary">Submit File</button> </form>

Never Save File With Its Original Name:

It is recommended that the file should not save it with its own name because it may override the existing file and another main reason is it may lead security issues (some malicious content can be saved to the server).





In C# we can generate a random name to file by using 'System.IO.Path.GetRandomFile()'. Now to test update the code in 'UploadFile' action method as below.

[HttpPost] public IActionResult UploadFile(FileUpload fileUpload) { // code hidden for display messages string filePath = $"{_env.WebRootPath}/images/{Path.GetRandomFileName()}.jpg"; }

Avoid Saving File In Application Tree Folders:

The recommended way of saving the file is to save outside of the application folders. Because of security issues, if we save the files in the outside directory we can scan those folders in background checks without affecting the application.

So to test the saving file outside the application folder, add the destination path in the 'appsettings.json' file.

{ "AppSettings":{ "FileRooTPath":"D:/FileStorage" } }

public class HomeController : Controller { // code hidden for display purpose private readonly Microsoft.Extensions.Configuration.IConfiguration _config; public HomeController( Microsoft.Extensions.Configuration.IConfiguration config) { _config =config; } }

[HttpPost] public IActionResult UploadFile(FileUpload fileUpload) { string filePath = $"{_config["AppSettings:FileRooTPath"]}/{Path.GetRandomFileName()}.jpg"; }

Upload Multiple Files:

Uploading multiple files can be done easily with minimum changes. .NET Core MVC file uploading with model binding can be done by using the following types.

Microsoft.AspNetCore.Http.IFormCollection

System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Http.IFormFile>

System.Collections.Generic.List<Microsoft.AspNetCore.Http.IFormFile>

Lets test multiple file upload sample by updating the FileUpload model property type with any of the above types as below.

Models/FileUpload.cs:

public class FileUpload { public List<IFormFile> FormFiles { get; set; } }

<input asp-for="@Model.FormFiles" type="file" multiple />

[HttpPost] public IActionResult UploadFile(FileUpload fileUpload) { if (fileUpload.FormFiles != null) { foreach (IFormFile formFile in fileUpload.FormFiles) { string filePath = $"{_config["AppSettings:FileRooTPath"]}/{Path.GetRandomFileName()}.jpg"; using (var stream = System.IO.File.Create(filePath)) { formFile.CopyTo(stream); } } } return Redirect("/"); }

Wrapping Up:

Hopefully, this article will help to understand file upload using buffer technique(this technique mean for small size files).NET Core MVC Application. I will love to have your feedback, suggestions and better techniques in the comment section.

Refer:

Follow Me:

In the following article, we create a sample for the file uploading using .NET Core MVC application.property in IFormFile holds content-type information from the client application.property in IFormFile gets the file name from the Content-Disposition header.method in IFormFile copies the contents of the uploaded file to the target stream.Let's create a model for form posting for the file upload as below.Now add the following logic to save the uploaded file.Now run the application and select a file to upload.After uploading we can test our image get added in the server at the destined path.Now while uploading file open developer tools of the browser and check request header you can observe the content-type and data how it is posting to the server as below.Now run the application and upload a file and check the file name.System.IO.Path.GetRandomFileName() has a side effect if the generation of files more than 65,535 files without deleting existing files in a specific folder then we will encounter an error of 'IOException'.So we need to overcome this by saving file folder tree maintaining or by tailing the TimeStamp or by tailing with GUID value we can overcome the issue.Now to read the 'appsettings.json' file values inject the 'Microsoft.Extensions.Configuration.IConfiguration' interface into the controller constructor as below.Now update the logic to fetch the root path in 'UpLoadFile' action method as follows.Now run the application and check the external folder path specified in 'appsettings.json'.In your personal system, we may not get folder permission issues, but in the production server very likely there will be a permission issue. So while giving permission issues only provide 'Read' and 'Write' and never give permission like 'Execute'.Now to support multiple file selection from Html can be done by decorating the Html input tag with 'multiple' attribute as below.Now update the action method to save multiple files as belowIf we observe there is nothing coding breaking changes here, only just looping the files.Now run the application and upload multiple files.