Reputation: 43
I am trying to write an action to upload a file and when I try to call GetFileName() method I get this error:
'IFormFile' does not contain a definition for 'GetFileName' and no accessible extension method 'GetFileName' accepting a first argument of type 'IFormFile' could be found (are you missing a using directive or an assembly reference?)
my controller uses the following namespaces:
using Microsoft.Extensions.FileProviders;
using System.IO;
using Microsoft.AspNetCore.Http;
and the action is:
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot", file.GetFileName());
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return RedirectToAction("Files");
}
Upvotes: 1
Views: 1972
Reputation: 76
To get the filename of the uploaded file using IFormFile we can get it using file.FileName.
Try this:
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return RedirectToAction("Files");
}
Upvotes: 2