如何将IFormFile保存到磁盘?

Ric*_*d77 37 c# asp.net-core-1.0

我正在尝试使用这段代码将文件保存在磁盘上.

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();
}
Run Code Online (Sandbox Code Playgroud)

我能代替IApplicationEnvironmentIHostingEnvironment,并ApplicationBasePathWebRootPath.

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

Nko*_*osi 62

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您不应使用用户输入中的 file.FileName 并将其与 path.combine 直接结合,因为此文件名可能包含到子目录(“../../”)的路由,您始终需要使用例如 Path.GetFullPath( generatePath) 如果返回值与您想要的上传目录相同。此外,请求中的文件名也不是唯一的。 (9认同)
  • 不要忘记关闭文件流。 (2认同)
  • @Signcodeindie`using`语句将在超出范围时关闭并处理流. (2认同)
  • 看来我们现在应该使用“IWebHostEnvironment”而不是“IHostingEnvironment” (2认同)
  • @cwhsu 是的。这是最新版本。当您查看框架更新的频率时,这是一篇非常古老的文章。我已经更新了帖子以反映当前的更改 (2认同)