Loading the .NET Core "IFormFile" file does not contain a definition for "SaveAsASync" and no extension method

I am trying to upload a file using ASP.NET core Web Api: How much 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 message “IFormFile” contains no definition for “SaveAsASync” and no extension method. Any idea?

+1
source share
2 answers

See https://github.com/aspnet/HttpAbstractions/issues/610 , which explains why the method was excluded

0

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


 }

:

formFile.SaveAsAsync("Your-File-Path"); // [ Async call ]
formFile.SaveAs("Your-File-Path");
0

All Articles