简体   繁体   中英

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?

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

}

Another way to do that.

View

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, 
          new { id = "myForm", enctype = "multipart/form-data" }))
{
    <input id="file" type="file" name="file" />
    <input type="submit" value="submit" />
}
<input type="button" value="Upload" onclick="uploadFile();" />

Javascript

function uploadFile() {
    $.ajax({
        url: '@Url.Action("InsertImage", "Product")',
        type: 'POST',
        data: new FormData(myForm),
        cache: false,
        contentType: false,
        processData: false,
        success: function () {
            alert('file uploaded');
        },
        error: function (xhr, error, status) {
            console.log(error, status);
        }
    });
}

Controller

[HttpPost]
public ActionResult InsertImage()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        // save file into Db
    }
    return new EmptyResult();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM