How to save uploaded file using IFormFile in ASP.NET 5 RC1 MVC
I followed the link suggested by @garethb here and used the extension method as suggested. It works!
Solution for ASP.NET RC1:
Namespace to include
using Microsoft.AspNet.Http;
Controller Action
[HttpPost]
public IActionResult Create(TeamVM vm)
{
FormFileExtensions.SaveAs(vm.UploadedLogo, "C:\pathTofile");
return View();
}
Credit for this answer goes to @garethb.
Solution for ASP.NET RC2:
Namespace to include
using Microsoft.AspNetCore.Http;
using System.IO;
Controller Action
[HttpPost]
public IActionResult Create(TeamVM vm)
{
// Make sure the path to the file exists
vm.UploadedLogo.CopyTo(new FileStream("C:\pathTofile", FileMode.Create));
return View();
}
Arthur Silva
Updated on August 04, 2022Comments
-
Arthur Silva almost 2 years
I'm using ASP.NET 5 RC with Visual Studio 2015.
I have a ViewModel defined:
public class TeamVM { public IFormFile UploadedLogo { get; set; } }
and a controller:
[HttpPost] public IActionResult Create(TeamVM vm) { vm.UploadedLogo.SaveAs("filename.txt"); // Problem here - There is no SaveAs method return View(); }
The problem is that intellisense shows that there is no
SaveAs()
method. I found out here that this interface actually does not have aSaveAs()
method.Also, I realized that if I change
IFormFile
toICollection<IFormFile>
and loop through, the collection theIFormFile
instances will have theSaveAs()
method defined.In my case I want to use
IFormFile
instead ofICollection<IFormFile>
.How would be the correct way to save file to system using
IFormFile
? -
Kfir Guy about 7 yearsYou can use
File.Create
instead ofnew FileStream
:File.Create("C:\pathTofile")