gpt4 book ai didi

按钮上的javascript文件阅读器单击错误: undefined refference

转载 作者:行者123 更新时间:2023-11-30 15:43:10 25 4
gpt4 key购买 nike

我试图从系统中获取本地文件,我进行了一些搜索并找到了一种方法,当我尝试在我的代码中实现它时,我得到了错误:

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>

我不知道如何使用包含的文件触发函数,因为我知道它正在寻找被单击的按钮中的值

最佳答案

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

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 .

关于按钮上的javascript文件阅读器单击错误: undefined refference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com