2015-12-30 38 views
3

我想讀取angularjs中上傳的圖像文件的數據。但正如所料,文件讀取器onload功能無法正常工作。角度指令 - 文件讀取器沒有射擊..在文件加載

任何人都可以幫助我解決這個問題並閱讀圖像文件以獲取數據。

這裏是我的代碼:

app.directive('uploadImageFile', function() { 

    return { 

    link : function (scope, element, attrs) { 

     var inputFile = element.find('.upload-field'); 

     element.on('click', function() { 

     inputFile[0].click(); 

     }); 

     inputFile.on('change', function() { 


      var reader = new FileReader(); 

        reader.onload = function (loadEvent) { 

          console.log("load event", loadEvent.target.result); //nothing consoling here 

      } 

     }) 

    } 

    } 

}) 

Live Demo

回答

2

你沒有添加readAsDataURL API,這觸發了上變化收到

更正代碼加載事件和event對象:Plunkr

inputFile.on('change', function (e) { 
     console.log("Changed"); 
     var reader = new FileReader(); 
     reader.onload = function (loadEvent) { 
      console.log("load event", loadEvent.target.result); 
     } 
     reader.readAsDataURL(e.target.files[0]); 
}) 
+0

如何防止用戶上傳圖像文件以外的其他用戶?你有什麼主意嗎? - 提前致謝。 – 3gwebtrain

+2

參考這個http://stackoverflow.com/questions/8938124/how-to-filter-input-type-file-dialog-by-specific-file-type – Nirus