weixin_33693070 2016-12-20 11:41 采纳率: 0%
浏览 19

jQuery-获取文件输入元素?

I have the following markup:

  <div class="file-container">
        <input type="file" name="file" id="file"  />
  </div>

I can get the uploaded file in my handler and ajax call as follows:

 $(document).on("change", ".file-container :file", function () {

    $.ajax({
        url: "xyz",
        type: "POST",
        files: $("form :file"),
        processData: false,
        dataType: "json"
    }).complete(function (data) {
       // do stuff

    });
});

But lets say i have two file inputs as follows:

 <div class="file-container">
    <input type="file" name="file1" id="file1"  />
 </div>

 <div class="file-container">
    <input type="file" name="file2" id="file2"  />
 </div>

On file1 change, how do i get the file element of file1 in my jQuery onchange handler and ajax call i.e what do i change this line to:

$(document).on("change", ".file-container :file", function () 

And this line:

files: $("form :file"),

The following doesnt work:

  $(document).on("change", ".file-container #file1", function () {

    $.ajax({
        url: "xyz",
        type: "POST",
        files: $("form #file1"),
        processData: false,
        dataType: "json"
    }).complete(function (data) {
       // do stuff

    });
  });

  $(document).on("change", ".file-container #file2", function () {

    $.ajax({
        url: "xyz",
        type: "POST",
        files: $("form #file2"),
        processData: false,
        dataType: "json"
    }).complete(function (data) {
       // do stuff

    });
});
  • 写回答

2条回答 默认 最新

  • weixin_33701564 2016-12-20 11:46
    关注

    This happens because the value of the input field (the selected filepath) does not change if you select the same file again.

    You can set the value in the onChange() event to an empty string and submit your form only if the value is not empty. Have a look at my sample and this link link

    Sample

     $(document).on("change",".file-container input.file", function () {
        if ($(".file-container input.file").val() == "") {
            return;
        }
        // get the inputs value
        var fileInputContent = $(".file-container input.file").val();
        // your ajax submit
        alert("submit value of the file input field=" + fileInputContent);
        // reset the field
        $(".file-container input.file").replaceWith('<input type="file" class="file" name="file" />');
    });​
    
    评论

报告相同问题?