ASP NET使用jQuery和AJAX上传图像

时间:2017-09-14 19:58:36

标签: javascript jquery asp.net ajax

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

所以我有这个:

HTML

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

的jQuery

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

问题是public class Department { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } public int? ParentId { get; set; } public virtual Department Parent { get; set; } public virtual ICollection<Department> Children { get; set; } private IList<Department> allParentsList = new List<Department>(); public IEnumerable<Department> AllParents() { var parent = Parent; while (!(parent is null)) { allParentsList.Add(parent); parent = parent.Parent; } return allParentsList; } } 变量无论如何都是null。我做错了什么?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以自己手动设置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)
{

}

答案 1 :(得分:0)

另一种方法。

查看

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