简体   繁体   English

使用jQuery和AJAX的ASP NET上传图像

[英]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). 我想做的事情在理论上很简单:我想使用ASP.NET,jQuery和AJAX上传图像,而无需提交表单(这一部分很重要)。

So I have this: 所以我有这个:

HTML HTML

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

jQuery 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. 问题在于无论如何file变量始终为null。 What I'm doing wrong? 我做错了什么? Can anybody helps? 有人可以帮忙吗?

You can manually set the FormData keys and values yourself. 您可以自己手动设置FormData键和值。

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

Create FormData and set a new key/value 创建FormData并设置一个新的键/值

$("#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 使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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