Javascript required
Skip to content Skip to sidebar Skip to footer

.net Core Mvc Upload File With Other String Data

File Upload is the process of uploading files from the user's arrangement to the web application's storage. ASP.Cyberspace Core MVC actions support uploading of 1 or more files using simple model binding.

We accept covered the file upload support in ASP.NET Cadre Web API in detail in the commodity Uploading Files With .Net Cadre Web API and Angular . There we looked at how to upload a file using an angular app on the client-side and an ASP.NET Core Web API on the server-side.

In this commodity, we are going to look at how to achieve the same functionality in an ASP.Cyberspace Core MVC awarding.


VIDEO: Uploading Files with ASP.NET Core Web API and Angular video.


If you've missed some of the previous articles in the serial we recommend visiting the serial page: ASP.NET Core MVC Series.

To download this article'south source code visit: File Upload in ASP.NET Core MVC.

Allow's get down to it.

Creating a File Input Control

To upload files, allow's create a new ASP.Internet Core MVC application, new FileUploadController and pattern an HTML class with a file input control for the Index action:

<form method="mail" enctype="multipart/course-data" asp-controller="FileUpload" asp-action="Alphabetize">     <div class="class-group">         <div course="col-medico-x">             <p>Upload one or more than files using this class:</p>             <input type="file" name="files" multiple />         </div>     </div>     <div form="form-group">         <div class="col-doctor-10">             <input type="submit" value="Upload" />         </div>     </div> </form>

In order to support file uploads, we must specify the enctype as multipart/form-data . The enctype attribute specifies how the class data should exist encoded when submitting it to the server. The enctype aspect tin exist used but if the form method is POST .

The file input element supports uploading multiple files. By removing the multiple attribute on the input element, we can restrict information technology to support just a unmarried file.

The Function of Model Bounden

We can access the individual files uploaded to the awarding through Model Binding using the IFormFile interface. Model Binding in ASP.Internet Cadre MVC maps information from HTTP requests to action method parameters. IFormFile represents a file that is sent with the HttpRequest and has the following construction:

public interface IFormFile {     string ContentType { get; }     cord ContentDisposition { get; }     IHeaderDictionary Headers { become; }     long Length { go; }     string Name { become; }     cord FileName { get; }     Stream OpenReadStream();     void CopyTo(Stream target);     Task CopyToAsync(Stream target, CancellationToken cancellationToken = zero); }          

As a security consideration, We should never rely on or trust the FileName property without validation.

When uploading files using model binding and the IFormFile interface, the action method can take either a single IFormFile or an IEnumerable<IFormFile> representing multiple files. We can loop through one or more uploaded files, relieve them to the local file organization and and so employ the files as per our application's logic:

public course FileUploadController : Controller {     ...      [HttpPost("FileUpload")]     public async Task<IActionResult> Index(List<IFormFile> files)     {         long size = files.Sum(f => f.Length);                                  var filePaths = new List<string>();         foreach (var formFile in files)         {             if (formFile.Length > 0)             {                 // full path to file in temp location                 var filePath = Path.GetTempFileName(); //we are using Temp file proper noun just for the example. Add your own file path.                 filePaths.Add together(filePath);                  using (var stream = new FileStream(filePath, FileMode.Create))                 {                     await formFile.CopyToAsync(stream);                 }             }         }          // procedure uploaded files         // Don't rely on or trust the FileName property without validation.          render Ok(new { count = files.Count, size, filePaths });     } }

Permit's place a breakpoint on the Index() method and run the awarding:

upload files screen

One time we choose files and click Upload, nosotros can debug the code to run across how files are uploaded to the server file system.

Here we but render the total number and size of files uploaded along with file paths.

Files uploaded using the IFormFile technique are buffered in memory or on disk on the webserver before existence processed. Inside the action method, the IFormFile contents are accessible every bit a stream. In addition to the local file arrangement, files tin be streamed to Azure Blob storage or Entity Framework.

OK, that's it for the file upload, let'south summarize what we've learned.

Decision

In this article we accept learned the following topics:

  • Creating a file upload control in ASP.Internet Cadre MVC Application
  • Utilize model binding to get the uploaded files
  • Read and copy files to stream

In the adjacent function of this series, nosotros'll look at Dependency Injection in ASP.Internet Core MVC.

tarenorererwithir.blogspot.com

Source: https://code-maze.com/file-upload-aspnetcore-mvc/