Asp.net Core Simple Example Uploading a File
File Upload is the procedure of uploading files from the user's system to the web application'due south storage. ASP.NET Core MVC actions back up uploading of one or more than files using simple model binding.
We accept covered the file upload support in ASP.NET Core Web API in detail in the commodity Uploading Files With .Cyberspace Core Web API and Angular . At that place we looked at how to upload a file using an angular app on the customer-side and an ASP.Cyberspace Cadre Web API on the server-side.
In this article, nosotros are going to look at how to reach the same functionality in an ASP.Internet Core MVC application.
VIDEO: Uploading Files with ASP.Cyberspace Core Web API and Angular video.
If y'all've missed some of the previous manufactures in the series we recommend visiting the series page: ASP.NET Core MVC Series.
To download this article'south source lawmaking visit: File Upload in ASP.Internet Core MVC.
Let'southward get down to it.
Creating a File Input Command
To upload files, let's create a new ASP.Internet Core MVC awarding, new FileUploadController and blueprint an HTML form with a file input control for the Alphabetize action:
<form method="post" enctype="multipart/form-data" asp-controller="FileUpload" asp-activeness="Alphabetize"> <div grade="form-group"> <div grade="col-md-10"> <p>Upload one or more files using this grade:</p> <input blazon="file" proper name="files" multiple /> </div> </div> <div course="form-group"> <div class="col-md-10"> <input type="submit" value="Upload" /> </div> </div> </class>
In society to support file uploads, we must specify the enctype
equally multipart/form-data
. The enctype
attribute specifies how the form data should be encoded when submitting it to the server. The enctype
aspect can 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 it to support simply a unmarried file.
The Role of Model Binding
Nosotros can access the private files uploaded to the application through Model Binding using the IFormFile
interface. Model Binding in ASP.Net Core MVC maps data from HTTP requests to action method parameters. IFormFile
represents a file that is sent with the HttpRequest
and has the post-obit structure:
public interface IFormFile { cord ContentType { get; } string ContentDisposition { become; } IHeaderDictionary Headers { go; } long Length { go; } cord Proper name { go; } string FileName { get; } Stream OpenReadStream(); void CopyTo(Stream target); Task CopyToAsync(Stream target, CancellationToken cancellationToken = nothing); }
Equally 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 tin take either a single IFormFile
or an IEnumerable<IFormFile>
representing multiple files. We can loop through i or more uploaded files, save them to the local file system and then use the files every bit per our application's logic:
public class FileUploadController : Controller { ... [HttpPost("FileUpload")] public async Chore<IActionResult> Index(Listing<IFormFile> files) { long size = files.Sum(f => f.Length); var filePaths = new Listing<string>(); foreach (var formFile in files) { if (formFile.Length > 0) { // full path to file in temp location var filePath = Path.GetTempFileName(); //nosotros are using Temp file name just for the case. Add your own file path. filePaths.Add(filePath); using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } } } // process uploaded files // Don't rely on or trust the FileName belongings without validation. return Ok(new { count = files.Count, size, filePaths }); } }
Let's place a breakpoint on the Alphabetize()
method and run the application:
Once we cull files and click Upload, we can debug the code to see how files are uploaded to the server file system.
Here we just return 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 being candy. Within the action method, the IFormFile
contents are accessible as a stream. In addition to the local file system, files tin be streamed to Azure Blob storage or Entity Framework.
OK, that's information technology for the file upload, let's summarize what nosotros've learned.
Conclusion
In this commodity we accept learned the post-obit topics:
- Creating a file upload control in ASP.Net Core MVC Application
- Utilize model binding to get the uploaded files
- Read and copy files to stream
In the next office of this series, we'll look at Dependency Injection in ASP.NET Core MVC.
Source: https://code-maze.com/file-upload-aspnetcore-mvc/
Postar um comentário for "Asp.net Core Simple Example Uploading a File"