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?

Simon
  • 1,955
  • 5
  • 35
  • 49

1 Answers1

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
Community
  • 1
  • 1
Sagi Levi
  • 305
  • 1
  • 11
  • 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. – Simon Nov 26 '15 at 14:36
  • 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 – Sagi Levi Nov 26 '15 at 14:40
  • Thank you. It is clear now, but why he is doing this? – Simon Nov 27 '15 at 00:04
  • 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. – Sagi Levi Nov 27 '15 at 05:15
  • Yes, but why controller has it's own implementation and didn't include request object into it? – Simon Nov 27 '15 at 12:05
  • The HttpContextBase is mainly used to enable unit testing – Sagi Levi Nov 28 '15 at 11:18