How to save uploaded file using IFormFile in ASP.NET 5 RC1 MVC

23,305

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();
}    
Share:
23,305
Arthur Silva
Author by

Arthur Silva

Updated on August 04, 2022

Comments

  • Arthur Silva
    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 a SaveAs() method.

    Also, I realized that if I change IFormFile to ICollection<IFormFile> and loop through, the collection the IFormFile instances will have the SaveAs() method defined.

    In my case I want to use IFormFile instead of ICollection<IFormFile>.

    How would be the correct way to save file to system using IFormFile?

  • Kfir Guy
    Kfir Guy about 7 years
    You can use File.Create instead of new FileStream : File.Create("C:\pathTofile")