File upload .NET Core 'IFormFile' does not

2019-07-09 00:15发布

I'm trying to upload a file using ASP.NET Core Web Api. As many i found this code:

namespace ModelBindingWebSite.Controllers
{
  public class HomeController : Controller
  {
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                await file.SaveAsAsync(Path.Combine(uploads, fileName));
            }
        }
        return View();
    }
}

I get the error IFormFile does not contain a definition for SaveAsASync and no extension method. Any idea?

2条回答
聊天终结者
2楼-- · 2019-07-09 00:28

You can simply build a handy extension for later use

 using System.IO;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;

 public static class FileSaveExtension
 {
     public static async Task SaveAsAsync(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             await formFile.CopyToAsync(stream);
         }
     }

     public static void SaveAs(this IFormFile formFile, string filePath)
     {
         using (var stream = new FileStream(filePath, FileMode.Create))
         {
             formFile.CopyTo(stream);
         }
     }


 }

Implementation:

formFile.SaveAsAsync("Your-File-Path"); // [ Async call ]
formFile.SaveAs("Your-File-Path");
查看更多
forever°为你锁心
3楼-- · 2019-07-09 00:43

Please see https://github.com/aspnet/HttpAbstractions/issues/610 which explains why the method has been superceded

查看更多
登录 后发表回答