0

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?

8
  • did you add enctype="multipart/form-data" attribute to your form tag? Commented Sep 14, 2017 at 20:06
  • One would assume, that your AJAX call is not triggered before you actually choose a file, right? Commented Sep 14, 2017 at 20:08
  • @Dejavu I believe that this doesn't change anything because the trigger of the AJAX function isn't the form submitting Commented Sep 14, 2017 at 20:08
  • So what do you get console.log(form_data) when you submit it? Commented Sep 14, 2017 at 20:09
  • @entiendoNull No Sr. It's being triggered by a button that's only available after it checks the file size and other things. Commented Sep 14, 2017 at 20:10

1 Answer 1

1

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)
{

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

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.