2016-11-07 55 views
1

我试图从系统中获取本地文件,我做了一些搜索,并绕过这样做的方式,当我试图在我的代码中实现它时,我得到了错误:按钮上的JavaScript文件阅读器点击错误:undefined refference

Uncaught TypeError: Cannot read property 'type' of undefined

document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false); 
 

 
function handleFileSelect(evt) { 
 
    var files = evt.target.files; 
 

 
    if(files.type.match('image.*')) { 
 
     var reader = new FileReader(); 
 
     reader.onload = (function(theFile) { 
 
      
 
     })(files); 
 

 
     var catIMG = reader.readAsBinaryString(files); 
 
     alert(catIMG);  
 
    } 
 
}
<input type="file" name="cat_path_orig" id="cat-path-orig"> 
 
<button class="btn btn-primary" id="add-new-cat">add</button>

我不知道如何触发功能,包括在文件,因为我知道它看起来会针对与被点击

在按钮的值
+0

你在哪里得到错误?什么线? – epascarello

+0

@ T.J.Crowder我提供了片段 – Grey

+0

@epascarello我在发生错误的行上添加了一条评论 – Grey

回答

2

事件对象click没有files属性。我认为你正在寻找的files属性input type="file"对象:

document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false); 
 

 
function handleFileSelect(evt) { 
 
    var files = document.getElementById("cat-path-orig").files; // **** 
 

 
    console.log("files.length: " + files.length); 
 
    Array.prototype.forEach.call(files, function(file) { 
 
    console.log(file.name + ": " + file.type); 
 
    }); 
 
}
<input type="file" name="cat_path_orig" id="cat-path-orig"> 
 
<button class="btn btn-primary" id="add-new-cat">add</button>

一对夫妇的其他注意事项:

  1. 你会想看看type每个文件的属性(参见上面的代码片段)。在您的示例中,将只有一个(因为input type="file"上没有multiple属性),所以您可以只使用files[0]而不是上面使用的循环。

  2. 您使用readAsBinaryString也是不正确的; here's an answer with a correct example

+0

完美的答案,再次,抱歉的混乱,阿蒙德荷兰错误是非常不同于英语错误,我会尽我所能,给予正确的英语错误时间。 – Grey