23

I referred this, which suggests that I can use IHttpContextAccessor to access HttpContext.Current. But I want to specifically receive files which that object doesn't seem to have.

So is there any alternative for Httpcontext.Current.Request.Files in Asp.Net Core 2.0

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Karan Desai
  • 3,012
  • 5
  • 32
  • 66

2 Answers2

29

Inside controller context and in action you can access files via HttpContext.Request.Form.Files:

public IActionResult Index()
{
    var files = HttpContext.Request.Form.Files;

    return View();
}

and outside controller you have to inject IHttpContextAccessor.

for upload file read File uploads in ASP.NET Core.

Mohsen Esmailpour
  • 11,224
  • 3
  • 45
  • 66
5

Uploading file in Asp.Net Core 2.0 is done with an interface IFormFile that you would take as a parameter in your post action.

Lets say you have an ajax post that will call the POST action and upload a file. You would first create the form data.

var data = new FormData();

data.set("file", $("#uploadControl").val())

$.ajax({
   type: "POST",
   url: "upload",
   data: data,
   contentType: false,
   processData: false
});

Your action would look like this

[HttpPost]
public IActionResult Upload(IFormFile file)
{
   //save the file
}

Please do not copy/paste this as this is just the general idea of how to do it.

Robert
  • 2,407
  • 1
  • 24
  • 35