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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();
}

Method 2

You can simply create your own file save extension for IFormFile.

Check out the code in this link


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x