Jquery / ajax文件上传

时间:2016-02-09 18:04:05

标签: javascript jquery ajax

未捕获的TypeError:无法读取未定义的属性“长度”

我有3个文件字段,每个字段都有自己独立的上传按钮。问题是文件字段是未定义的。

JavaScript的:

$('.imgAction').on('click', function () {

    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening
    var imgID = $(this).attr('data-id');
    var fileSelect =  $(this).closest('div').find('input[type=file]');

    var files = fileSelect.files;

    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file" + x, files[x]);
            }

            $.ajax({
                type: "POST",
                url: '/AdminPanel/Catalog/ImgUpload/' + @Model.productID + "/" + imgID,
                contentType: false,
                processData: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3 + " " + p4;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).Message;
                    console.log(err);
                }
            });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
        }
    }
});

HTML

<div>
@if (Model.productType == 1)
{
    string imgPath1 = "assets/img/catalog/phones/" + @Model.Make + "-" + @Model.Model + "-" + @Model.carrier1 + "-1.jpg";
    string imgPath2 = "assets/img/catalog/phones/" + @Model.Make + "-" + @Model.Model + "-" + @Model.carrier1 + "-2.jpg";
    string imgPath3 = "assets/img/catalog/phones/" + @Model.Make + "-" + @Model.Model + "-" + @Model.carrier1 + "-3.jpg";

    <div style="width: 20%;float: left;">
"
        <img width="200" id="img1" src="~/@imgPath1" />
        <input type="file" class="imgFile" />
        <a href="#" class="imgAction" data-id="1">UPLOAD</a>
    </div>
    <div style="width: 20%;float: left;">
        <img width="200" id="img2" src="~/@imgPath2" />
        <input type="file"  class="imgFile" />
        <a href="#" class="imgAction" data-id="2">UPLOAD</a>
    </div>
    <div style="width: 20%;float: left;">
        <img width="200" id="img3" src="~/@imgPath3" />
        <input type="file"  class="imgFile"/>
        <a href="#" class="imgAction" data-id="3" >UPLOAD</a>
    </div>
}
</div>

2 个答案:

答案 0 :(得分:3)

你应该得到jQuery find方法的第一个元素,它应该是这样的:

var files = fileSelect[0].files;

答案 1 :(得分:0)

您似乎尝试上传而不使用文件字段与按钮或图像之间的任何直接关联(无论imgAction引用)。如果两者是相邻的元素,那么您可能需要触发上传事件。

var fileSelect = $(this).closest('div').find('input[type=file]').click()

查看jquery click docs