如何在ASP.NET 5 RC1 MVC中使用IFormFile保存上传的文件 [英] How to save uploaded file using IFormFile in ASP.NET 5 RC1 MVC
问题描述
我正在将ASP.NET 5 RC与Visual Studio 2015一起使用.
I'm using ASP.NET 5 RC with Visual Studio 2015.
我定义了一个ViewModel:
I have a ViewModel defined:
public class TeamVM
{
public IFormFile UploadedLogo { get; set; }
}
和一个控制器:
[HttpPost]
public IActionResult Create(TeamVM vm)
{
vm.UploadedLogo.SaveAs("filename.txt"); // Problem here - There is no SaveAs method
return View();
}
问题是智能感知表明没有SaveAs()
方法.我发现此处该接口实际上没有SaveAs()
方法.
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.
此外,我意识到,如果将IFormFile
更改为ICollection<IFormFile>
并进行遍历,则IFormFile
实例的集合将定义SaveAs()
方法.
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.
就我而言,我要使用IFormFile
而不是ICollection<IFormFile>
.
In my case I want to use IFormFile
instead of ICollection<IFormFile>
.
如何使用IFormFile
将文件保存到系统的正确方法?
How would be the correct way to save file to system using IFormFile
?
推荐答案
I followed the link suggested by @garethb here and used the extension method as suggested. It works!
ASP.NET RC1解决方案:
要包含的命名空间
using Microsoft.AspNet.Http;
控制器动作
[HttpPost]
public IActionResult Create(TeamVM vm)
{
FormFileExtensions.SaveAs(vm.UploadedLogo, "C:\pathTofile");
return View();
}
该答案的信用转到@garethb.
Credit for this answer goes to @garethb.
ASP.NET RC2解决方案:
要包含的命名空间
using Microsoft.AspNetCore.Http;
using System.IO;
控制器动作
[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();
}
这篇关于如何在ASP.NET 5 RC1 MVC中使用IFormFile保存上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!