2014-09-21 47 views
0

我試圖附加文件到FormData來處理通過AJAX上傳的文件,並在閱讀並繼續查找解決方案而無需使用外部插件我發現this,我想用我的代碼,所以我做了這個:使用File API讀取文件,使用File API顯示「TypeError:e is undefined」

$(function() { 
    $('.smart-form').on('submit', function (e) 
    { 
     var files; 

     e.stopPropagation(); // Stop stuff happening 
     e.preventDefault(); // Totally stop stuff happening 

     if ($(".state-error").length < 1) { 
      // Create a formdata object and add the files 
      var data = new FormData(); 

      // Check for the various File API support. 
      if (window.File && window.FileReader && window.FileList && window.Blob) { 
       // Grab the files and set them to our variable 
       files = e.target.files; 

       $.each(files, function (key, value) 
       { 
        data.append(key, value); 
       }); 
      } 

      // Create a jQuery object from the form 
      $form = $(e.target); 

      // Serialize the form data 
      var formData = $form.serializeArray(); 

      $.ajax({ 
       async: false, 
       url: '{{ path('update-product', {'id': id}) }}', 
       type: 'POST', 
       data: formData, 
       cache: false, 
       success: function (data, textStatus, jqXHR) 
       { 
        if (typeof data.error === 'undefined') 
        { 
         // Success so call function to process the form 
         console.log("SUCCESS"); 
        } 
        else 
        { 
         console.log("ERRORS"); 
        } 
       }, 
       error: function (jqXHR, textStatus, errorThrown) 
       { 
        // Handle errors here 
        console.log("ERRORS"); 
       }, 
       complete: function() 
       { 
        // STOP LOADING SPINNER 
       } 
      }); 
     } 
    }); 
}); 

但我在Firebug控制檯收到此錯誤:

TypeError: e is undefined

而且我不ABL e找到我的錯誤或發生了什麼。 Here是一個帶有測試代碼的小提琴,可以幫助我並告訴我我做錯了什麼嗎?

更新

的錯誤不是在的jsfiddle一樣的,如果你在Firebug控制檯看看錯誤trown是這個,而不是:

TypeError: obj is undefined 
    length = obj.length, 

回答

1

你的問題是這一行:

files = e.target.files; 

在您提供的鏈接中,他將事件處理程序附加到文件輸入elem的更改事件而不是提交按鈕:

document.getElementById('files').addEventListener('change', handleFileSelect, false); 

所以e.target將文件輸入元素和e.target.files將工作。

你已經改變了代碼,你在提交按鈕點擊處理程序中調用它。因此,e.target引用提交按鈕,而e.target.files則不涉及任何內容。

所以你的代碼改成這樣,它會工作:

files = $('form #product_imageFile_file')[0].files; 

看到這裏的工作小提琴:http://jsfiddle.net/manishie/xyqoozb5/2/

相關問題