MWsan
MWsan

Reputation: 457

ASP NET upload image with jQuery and AJAX

What I'm trying to do is theoretically simple: I want upload an image using ASP.NET, jQuery and AJAX, without submitting a form (this part is important).

So I have this:

HTML

<input type="file" accept="image/*" id="imguploader">   

jQuery

var file_data = $("#imguploader").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);

        $.ajax({
            type: "POST",
            url: '@Url.Action("InsertImage", "Product")',
            data: { file: form_data },
            contentType: false,
            processData: false,
            success: function (response) {
                alert('succes!!');
            },
            error: function (error) {
                alert("errror");
            }
        });

Controller

public ActionResult InsertImage(HttpPostedFileBase file) {

   //blabla and the code to insert in the database.

   return Content("");
}

What else I have tried:

// instead of using FormData, I tried to direclty capture the file using these:

var file = $("#imguploader").file;
//and
var file = $("#imguploader")[0].files;

//Same result (null).

The problem is that the file variable is always null no matter what. What I'm doing wrong? Can anybody helps?

Upvotes: 0

Views: 3314

Answers (1)

Jasen
Jasen

Reputation: 14250

You can manually set the FormData keys and values yourself.

<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>

Create FormData and set a new key/value

$("#btnUpload").on("click", function(e) {
    e.preventDefault();

    var file = $("#imguploader").get(0).files[0];
    var formData = new FormData();
    formData.set("file", file, file.name);

    $.ajax({
        url: '@Url.Action("InsertImage", "Product")',
        method: "post",
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    })
    .then(function(result) {

    });
});

The controller

[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{

}

Upvotes: 1

Related Questions