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:
Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below. Check the link to use the Visual Studio Code for .NET Core Application.
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.
ContentType property in IFormFile holds content-type information from the client application.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"
FileName property in IFormFile gets the file name from the Content-Disposition header.
CopyTo(Stream target) method in IFormFile copies the contents of the uploaded file to the target stream.
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.
Let's create a model for form posting for the file upload as below.Models/FileUpload.cs:
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 }Now add the following logic to save the uploaded file.
Controllers/HomeController.cs:
[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>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.
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"; }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.
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" } }Now to read the 'appsettings.json' file values inject the 'Microsoft.Extensions.Configuration.IConfiguration' interface into the controller constructor as below.
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; } }Now update the logic to fetch the root path in 'UpLoadFile' action method as follows.
[HttpPost] public IActionResult UploadFile(FileUpload fileUpload) { string filePath = $"{_config["AppSettings:FileRooTPath"]}/{Path.GetRandomFileName()}.jpg"; }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'.
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; } }Now to support multiple file selection from Html can be done by decorating the Html input tag with 'multiple' attribute as below.
Views/Home/Index.cshtml:
<input asp-for="@Model.FormFiles" type="file" multiple />Now update the action method to save multiple files as below
Controllers/HomeController.cs:
[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("/"); }If we observe there is nothing coding breaking changes here, only just looping the files.
Now run the application and upload multiple files.
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.
Comments
Post a Comment