2013-09-25 70 views
0

我正在嘗試編寫一個java腳本來讀取chrome中的文件,並使用chrome的javascript調試器。 這裏是腳本:在chrome中讀取文件

function myFunction() 
{ 
alert("I am an alert box!"); 
var e ; 
var contents; 
var control = document.getElementById("myfile"); 
    files = control.files; 
console.log("Filename: " + files[0].name); 
var reader = new FileReader(); 
reader.readAsText(files[0]); 

reader.onload = function (e) { 


    contents = e.target.result; 

    }; 

console.log("File contents: " + contents); 
console.log("I am an alert box!");console.log("I am an alert box!"); 



} 





</script> 

當我運行的代碼內容的變量是不確定的。大量的討論已經進入到這一點,但我還沒有找到解決辦法。我正在使用--allow-file-acess-from-files選項。 現在下面的代碼工作在一個陌生的方式:

<script> 
function myFunction() 
{ 
alert("I am an alert box!"); 
var e ; 
var contents; 
var control = document.getElementById("myfile"); 
    files = control.files; 
console.log("Filename: " + files[0].name); 
var reader = new FileReader(); 
reader.readAsText(files[0]); 

reader.onload = function (e) { 
    contents = e.target.result ; 
    }; 
console.log(e.target.result); 
console.log("I am an alert box!");console.log("I am an alert box!"); 
} 
</script> 

它拋出一個錯誤,這是「遺漏的類型錯誤:無法未定義讀取屬性‘目標’」 然而,在手錶式窗口中的下列變量顯示,正在讀取文件。

event.target.result:「固件文件 ↵:10000000782600204D4B0000B94B0000B94B000092 ↵:10001000B94B0000B94B0000B94B000000000000D4 ↵:10002000000000000000000000000000B94B0000CC ↵:10003000B94B000000000000B94B0000210B00008C ↵:10004000B94B0000B94B0000B94B0000B94B0000A0 ↵:10005000B94B0000B94B0000B94B0000B94B000090 ↵:10006000B94B0000B94B0000B94B0000B94B000080 ↵:10007000B94B0000B94B0000B94B0000B94B000070 ↵:10008000B94B0000B94B0000B94B0000B94B000060 和e.target.result和contents變量的輸出相同。

爲什麼代碼行爲如此惡劣? 請幫助我。我不熟悉javascripting。

+0

可能重複http://stackoverflow.com/questions/4100927/chrome -filereader) –

回答

1

e.target將在您的第二個console.log中未定義 - 底部 - 只有一個在您的onload函數內,因此已設置e

第二個是你在頂部定義的var e ;,它是空的,因此e.target.result是無效的。

E:換句話說,刪除這條線,或將其移動到函數:

bogus line

[鉻的FileReader](的
+0

在我完成你告訴我的更改之後,當我遍歷代碼時,它永遠不會進入onload函數。因此,我在那裏發表聲明,以便它至少進入onload函數。 – RAN