I'm recently working on a ReactJS app that's calling an API (developed with .NET Core 2.0).
My question is how to use HttpPostedFileBase
in an .NET Core 2.0 API in order to get file content and save it in database.
The HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. The HttpPostedFileBase class lets you create derived classes that are like the HttpPostedFile class, but that you can customize and that work outside the ASP.NET pipeline.
What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.
You will need to right click your project in Solution Explorer, then select Add then New Item from the Context menu. Then from the Add New Item Dialog window, select Web Configuration File option and click Add Button. Finally, in the Web. Config file, set the maxAllowedContentLength setting to 100 MB as shown below.
In order to support file uploads, HTML forms must specify an encoding type ( enctype ) of multipart/form-data . The individual files uploaded to the server can be accessed through Model Binding using IFormFile. The sample app demonstrates multiple buffered file uploads for database and physical storage scenarios.
You don't have HttpPostedFileBase
in ASP.NET Core 2.0, but you can use IFormFile
.
[HttpPost("UploadFiles")] public async Task<IActionResult> Post(List<IFormFile> files) { long size = files.Sum(f => f.Length); // full path to file in temp location var filePath = Path.GetTempFileName(); foreach (var formFile in files) { if (formFile.Length > 0) { 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, filePath}); }
More here: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
IFormFile
is in the following namespace Microsoft.AspNetCore.Http
.
HttpPostedFileBase
doesn't exist in ASP.NET Core. You should use IFormFile
now, instead. However, that only works when you send the request as multipart/form-data
, which you're likely not doing if you're working with a client-side framework like React. If you're posting JSON, you should set the JSON member that corresponds with your file property with the file encoded as a Base64 string. Server-side, you should then bind to byte[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With