如何将IFormFile保存到磁盘? [英] How to save IFormFile to disk?

查看:1080
本文介绍了如何将IFormFile保存到磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用这部分代码

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

I was able to replace IApplicationEnvironment with IHostingEnvironment, and ApplicationBasePath with WebRootPath.

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

It seems like IFormFile doesn't have SaveAsAsync() anymore. How do I save file to disk then?

推荐答案

自从核心版本发布以来,有些事情已经改变

A few things have changed since core's release candidates

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

这篇关于如何将IFormFile保存到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆