我正在尝试使用这段代码将一个文件保存在磁盘上。
IHostingEnvironment _hostingEnvironment;
public ProfileController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files)
{
foreach (var file in files)
{
var fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var filePath = _hostingEnvironment.WebRootPath + "\\wwwroot\\" + fileName;
await file.SaveAsAsync(filePath);
}
return View();
}我能够用IHostingEnvironment,代替IApplicationEnvironment,用WebRootPath代替ApplicationBasePath。
看起来IFormFile已经不再有IFormFile了。那么,如何将文件保存到磁盘?
发布于 2016-09-04 22:52:51
自从core发布候选人以来,有几件事情发生了变化
public class ProfileController : Controller {
private IWebHostEnvironment _hostingEnvironment;
public ProfileController(IWebHostEnvironment environment) {
_hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files) {
string uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
foreach (IFormFile file in files) {
if (file.Length > 0) {
string filePath = Path.Combine(uploads, file.FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create)) {
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
}发布于 2020-05-07 15:28:41
Core3.0中还有进一步的更改,因为IHostingEnvironment现在被标记为过时了。
using Microsoft.Extensions.Hosting;
public class ProfileController : Controller
{
private IHostEnvironment _hostingEnvironment;
public ProfileController(IHostEnvironment environment)
{
_hostingEnvironment = environment;
}https://stackoverflow.com/questions/39322085
复制相似问题