26

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

4
  • Are you trying to upload a file? Commented Nov 1, 2017 at 8:05
  • @Kirk Sorry yes, I have updated the question. It is IHttpContextAccessor. But its object does not have HttpContext.Current or Request.Files property. It is deprecated in Core I think. And I am not finding its alternative. Commented Nov 1, 2017 at 8:13
  • @Rob Yes. I am trying to find uploaded file. Commented Nov 1, 2017 at 8:14
  • Related post - MVC 6 HttpPostedFileBase? Commented Sep 21, 2021 at 11:30

2 Answers 2

31

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Woah..They migrated it to Form. I didn't notice it! Thanks :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.