Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
Arthur Silva Avatar asked May 11 '16 04:05

Arthur Silva


1 Answers

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();
}    
like image 142
Arthur Silva Avatar answered Oct 18 '22 21:10

Arthur Silva