0

I have HTML page and I call web api to upload file. My client side code is:

<input name="file" type="file" id="load-image" />
<script>
...
var data = new FormData();
var files = $("#load-image").get(0).files;
data.append("UploadedImage", files[0]);

var ajaxRequest = $.ajax({
          type: "POST",
          url: "/UploadImage",
          contentType: false,
          processData: false,
          data: data
 });

And server side code:

public class FileUploadController : ApiController
{
 [HttpPost]
 public void UploadImage()
 {
   if (HttpContext.Current.Request.Files.AllKeys.Any())...

It works. Now I would like to do the same in MVC project. I have client side code the same, but server side code is little different.

Base class of controller is Controller(not api controller) and when I try this:

public class FileUploadController : ApiController
    [HttpPost]
    public void UploadImage()
    {
if (HttpContext.Current.Request.Files.AllKeys.Any())

I get error that 'System.Web.HttpContextBase' does not contain a definition for 'Current'...

What should I change in MVC that file upload will work the same as in webApi? Client side code is the same?

3
  • Try using this System.Web.HttpContext.Current Commented Nov 26, 2015 at 10:04
  • 1
    Can you NOT do stuff like this please. Do it properly with a model passed to the route which contains the file. Commented Nov 26, 2015 at 10:16
  • Thank you Phil. Do you have some url with example or description how to pass model to a route? Commented Nov 26, 2015 at 14:34

1 Answer 1

1

There is a related question here: System.Web.HttpContextBase' does not contain a definition for 'Current' MVC 4 with Elmah Logging

Long story short: Controller has a HttpContext.Current of himself implemented as

public HttpContextBase HttpContext { get; }

therefore u should use:

System.Web.HttpContext.Current
Sign up to request clarification or add additional context in comments.

6 Comments

I have already did, but wanted to know, why? I will read long story. Otherwise i have an error in js file - instead of file it was image on canvas added into data.
The controller class defines the HttpContext therefore when you use HttpContext without namespace it will use this one, if you will use with full namespace you should use the same httpcontext as the WebApi
Thank you. It is clear now, but why he is doing this?
Because this is one of the compiler basics, he will always look in the class inner circle (methods, fields, properties) and then just look for it in the outer circle.
Yes, but why controller has it's own implementation and didn't include request object into it?
|

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.