Mvc Upload File Stream Not Read Again
File Upload is the procedure of uploading files from the user'southward system to the web awarding'southward storage. ASP.Cyberspace Cadre MVC actions support uploading of one or more files using elementary model binding.
We take covered the file upload back up in ASP.Internet Cadre Web API in detail in the article Uploading Files With .NET Core Spider web API and Athwart . In that location we looked at how to upload a file using an angular app on the client-side and an ASP.NET Core Spider web API on the server-side.
In this commodity, nosotros are going to look at how to achieve the same functionality in an ASP.Net Cadre MVC awarding.
VIDEO: Uploading Files with ASP.Internet Core WEB API and Angular video.
If you lot've missed some of the previous manufactures in the serial we recommend visiting the series page: ASP.NET Core MVC Series.
To download this article's source code visit: File Upload in ASP.Cyberspace Core MVC.
Permit's get down to it.
Creating a File Input Control
To upload files, let'south create a new ASP.NET Core MVC application, new FileUploadController and design an HTML form with a file input command for the Index action:
<form method="post" enctype="multipart/form-data" asp-controller="FileUpload" asp-activeness="Alphabetize"> <div form="form-group"> <div grade="col-md-10"> <p>Upload one or more files using this form:</p> <input type="file" proper noun="files" multiple /> </div> </div> <div class="form-group"> <div form="col-md-10"> <input type="submit" value="Upload" /> </div> </div> </form>
In social club to support file uploads, we must specify the enctype
as multipart/course-data
. The enctype
attribute specifies how the form data should be encoded when submitting it to the server. The enctype
attribute tin be used only if the form method is POST
.
The file input chemical element supports uploading multiple files. By removing the multiple
attribute on the input element, we tin restrict it to support just a single file.
The Role of Model Binding
We can access the individual files uploaded to the application through Model Binding using the IFormFile
interface. Model Binding in ASP.Internet Cadre MVC maps information from HTTP requests to activeness method parameters. IFormFile
represents a file that is sent with the HttpRequest
and has the following structure:
public interface IFormFile { string ContentType { get; } string ContentDisposition { go; } IHeaderDictionary Headers { get; } long Length { get; } string Name { get; } string FileName { get; } Stream OpenReadStream(); void CopyTo(Stream target); Task CopyToAsync(Stream target, CancellationToken cancellationToken = aught); }
As a security consideration, We should never rely on or trust the FileName
belongings without validation.
When uploading files using model binding and the IFormFile
interface, the activity method tin take either a unmarried IFormFile
or an IEnumerable<IFormFile>
representing multiple files. We can loop through i or more uploaded files, salve them to the local file arrangement and so apply the files as per our awarding'southward logic:
public grade FileUploadController : Controller { ... [HttpPost("FileUpload")] public async Job<IActionResult> Index(Listing<IFormFile> files) { long size = files.Sum(f => f.Length); var filePaths = new Listing<cord>(); 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 name merely for the example. 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 property without validation. return Ok(new { count = files.Count, size, filePaths }); } }
Permit'southward place a breakpoint on the Index()
method and run the application:
Once we choose files and click Upload, we tin can debug the lawmaking to see how files are uploaded to the server file system.
Here we simply 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 deejay on the webserver before being processed. Within the action method, the IFormFile
contents are accessible every bit a stream. In addition to the local file organization, files can be streamed to Azure Blob storage or Entity Framework.
OK, that'south it for the file upload, let's summarize what we've learned.
Decision
In this commodity we have learned the following topics:
- Creating a file upload control in ASP.NET Core MVC Application
- Utilize model bounden to get the uploaded files
- Read and copy files to stream
In the side by side function of this series, we'll look at Dependency Injection in ASP.Cyberspace Core MVC.
Source: https://code-maze.com/file-upload-aspnetcore-mvc/
0 Response to "Mvc Upload File Stream Not Read Again"
Post a Comment