繁体   English   中英

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

[英]ASP NET upload image with jQuery and AJAX

我想做的事情在理论上很简单:我想使用ASP.NET,jQuery和AJAX上传图像,而无需提交表单(这一部分很重要)。

所以我有这个:

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");
            }
        });

调节器

public ActionResult InsertImage(HttpPostedFileBase file) {

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

   return Content("");
}

我还尝试了什么:

// 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).

问题在于无论如何file变量始终为null。 我做错了什么? 有人可以帮忙吗?

您可以自己手动设置FormData键和值。

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

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

    });
});

控制器

[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{

}

另一种方式。

视图

@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);
        }
    });
}

调节器

[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