2016-07-22 77 views
3

HTMLjQuery的文件上傳最近的TR

<table> 
    <tr> 
     <td> <input type="file" /> </td> 
     <td> <input type="button" id="btn" /> </td>  
    </tr>   
    <tr> 
    <td> <input type="file" /> </td> 
      <td> <input type="button" id="btn" /> </td>  
    </tr> 

    <tr> 
     <td> <input type="file" /> </td> 
      <td> <input type="button" id="btn" /> </td>  
    </tr> 

</table> 

JQUERY

var formData = new FormData(); 
    var tr = $(this).closest('tr'); 
    var fup = $(tr).find("input[type='file']"); 
    var totalFiles = fup.length;//Here, getting total file count 
    for (var i = 0; i < totalFiles; i++) { 
     var file = fup.file[i];//I am getting exception here 
     formData.append("fupUpdate", file); 
     } 

我無法得到追加到FORMDATA的文件列表。

Error Message: "Cannot read property '0' of undefined" 

請幫助我解決問題。

回答

1

試試這個代碼

var fData = new FormData(); 
var tr = $('table').closest('tr'); 
var fup = $('tr').find("input[type='file']"); 
var totalFiles = fup.length;//Here, getting total file count 
    for (var i = 0; i < totalFiles; i++) { 
     var file = fup[i].files[0];//Exception will not occur here 
     console.log(file) 
     fData.append("fupUpdate", file); 
    } 

不要使用相同的名稱作爲FORMDATA

+0

非常感謝你。有效!!! – Pearl

1

你正在做正確的創建局部變量只需更換

var file = fup.file[i];//I am getting exception here 

var file = fup[i].files[0];// no Exception here. 

和這將工作正常。

+0

非常感謝。有效!!! – Pearl

1

我相信問題出在你選擇的輸入上。您可以使用下列選項:

$(":file") 

或者

$("table tr :input[type='file']").each(function (i,v) { 
     var file=$(v); 
     //Your code goes here 
}); 

工作實例JsFiddle