Alexandru
Alexandru

Reputation: 12912

Posting an image using a jQuery AJAX call to an MVC action

I have the following code:

$("#preview").click(function () {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("Preview")',
        data: {
            color: $("#color-picker").val(),
            logo: $("#fileInput")[0].files[0]
        },
        success: function (data) {
            alert("Success!");
        },
        dataType: "json"
    });
});

Which uses this element:

<input id="fileInput" type="file" />

Which tries to post an image to this MVC action:

[HttpPost]
public async Task<ActionResult> Preview(string color, HttpPostedFileBase logo)
{
    return Json("Success.");
}

Unfortunately, when I post, I get Uncaught TypeError: Illegal invocation in Chrome's logs. This error comes from the jQuery side of things according to the stack trace. There's nothing wrong with $("#color-picker").val() nor with $("#fileInput")[0].files[0] when I check them in Chrome Developer Tools' watch before the call happens (one is a string with the appropriate color code, the other is a File).

I did troubleshoot it to find the reason why this happens. It is because I try to pass $("#fileInput")[0].files[0] as a parameter, but I get the same error when I try to do it this way by appending the file. I am using the latest version of Chrome and I've been researching into a way to pass an image quite a bit. I have been checking lots of questions on Stack Overflow to try to find a solution but so far I could not find a good way to upload this file.

Does anyone know what kind of security concern causes file uploads to not be allowed like this and how I can upload an image in a similar fashion, or by what means I will have to do so? What alternatives are there? I can't seem to make anything work so far that I've come across on Stack.

Upvotes: 0

Views: 5657

Answers (1)

DarkVision
DarkVision

Reputation: 1423

you could do something like this in javascript

var fd = new FormData();
var files = $("#fileInput").get(0).files;

if(files.lenght > 0){
   fd.append("logo",files[0]);
}

$.ajax({
        type: 'POST',
        url: '@Url.Action("Preview")',
        data:fd,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (data) {
            alert("Success!");
        }
    });

on controller you can get image like this

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
   var picture = System.Web.HttpContext.Current.Request.Files["logo"];
}

Upvotes: 3

Related Questions