I'm trying to save a file on disk using this piece of code.
IHostingEnvironment _hostingEnvironment; public ProfileController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } [HttpPost] public async Task<IActionResult> Upload(IList<IFormFile> files) { foreach (var file in files) { var fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); var filePath = _hostingEnvironment.WebRootPath + "\\wwwroot\\" + fileName; await file.SaveAsAsync(filePath); } return View(); }
I was able to replace IApplicationEnvironment with IHostingEnvironment, and ApplicationBasePath with WebRootPath.
It seems like IFormFile doesn't have SaveAsAsync() anymore. How do I save file to disk then?
Save a Stream to a File using C# In the above code, CopyTo method Copies the contents of the uploaded file to the target stream. If using Asynchronous API then please use CopyToAsync method which helps in Asynchronously copying the contents of the uploaded file to the target stream without blocking the main thread.
Inside the action method, the IFormFile contents are accessible as a Stream. So for IFormFile , you need to save it locally before using the local path. After this, you can get the local file path, namely filePath . In the case of a large file, isn't it taking a lot of time to get the file path after saving it locally?
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.
A few things have changed since core's release candidates
public class ProfileController : Controller { private IWebHostEnvironment _hostingEnvironment; public ProfileController(IWebHostEnvironment environment) { _hostingEnvironment = environment; } [HttpPost] public async Task<IActionResult> Upload(IList<IFormFile> files) { string uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); foreach (IFormFile file in files) { if (file.Length > 0) { string filePath = Path.Combine(uploads, file.FileName); using (Stream fileStream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(fileStream); } } } return View(); } }
There are to be further changes in Core 3.0 as IHostingEnvironment is now marked as obsolete.
using Microsoft.Extensions.Hosting; public class ProfileController : Controller { private IHostEnvironment _hostingEnvironment; public ProfileController(IHostEnvironment environment) { _hostingEnvironment = environment; }
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