如何将IFormFile保存到磁盘?

时间:2016-09-04 22:37:44

标签: c# asp.net-core-1.0

我正在尝试使用this piece of code将文件保存到磁盘上。

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

我能够将 IApplicationEnvironment 替换为 IHostingEnvironment ,将 ApplicationBasePath 替换为 WebRootPath

似乎 IFormFile 不再具有 SaveAsAsync()。如何将文件保存到磁盘呢?

2 个答案:

答案 0 :(得分:55)

自核心发布候选人以来,一些事情发生了变化

public class ProfileController : Controller {
    private IHostingEnvironment _hostingEnvironment;

    public ProfileController(IHostingEnvironment environment) {
        _hostingEnvironment = environment;
    }

    [HttpPost]
    public async Task<IActionResult> Upload(IList<IFormFile> files) {
        var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
        foreach (var file in files) {
            if (file.Length > 0) {
                var filePath = Path.Combine(uploads, file.FileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create)) {
                    await file.CopyToAsync(fileStream);
                }
            }
        }
        return View();
    }
}

答案 1 :(得分:2)

由于IHostingEnvironment已被标记为过时,因此Core 3.0中会有进一步的更改。

using Microsoft.Extensions.Hosting;

public class ProfileController  : Controller
{
    private IHostEnvironment _hostingEnvironment;

    public ProfileController(IHostEnvironment environment)
    {
        _hostingEnvironment = environment;
    }