gpt4 book ai didi

javascript - 第一次拖放 FileReader() 事件但无法读取文件内容

转载 作者:行者123 更新时间:2023-11-30 20:41:22 25 4
gpt4 key购买 nike

您好,我需要有关如何让拖放读取拖放到放置区中的 .text 文件的帮助。我仍在探索 javascript,需要帮助来指导我了解我的代码有什么问题。 .

文本文件的内容应该显示在显示区域

引用:http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

提前致谢!

https://jsfiddle.net/d6nur0wc/1/

 (function() {
var dropzone = document.getElementById("dropzone");

dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";

console.log(event.dataTransfer.files[0]);

window.onload = function() {
var fileInput = document.getElementById('dropzone');
var fileDisplayArea = document.getElementById('displayarea');

fileInput.addEventListener('dropzone.ondrop', function(read) {
var file = fileInput.files[0];
var textType = /text.*/;

if (file.type.match(textType)) {
var reader = new FileReader();

reader.onload = function(read) {
fileDisplayArea.innerText = reader.result;
}

reader.readAsText(file);
}

else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
}

dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};

dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};

}())

最佳答案

你的代码应该是这样的。您必须删除 onload 事件监听器。它不能在这里兼容。

(function() {
var dropzone = document.getElementById("dropzone");

dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";

console.log(event.dataTransfer.files[0]);


var fileInput = document.getElementById('dropzone');
var fileDisplayArea = document.getElementById('displayarea');

var file = event.dataTransfer.files[0]
var textType = /text.*/;

if (file.type.match(textType)) {
var reader = new FileReader();

reader.onload = function(read) {
fileDisplayArea.innerText = reader.result;
}

reader.readAsText(file);
}

else {
fileDisplayArea.innerText = "File not supported!";
}
}

dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};

dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};

}())

关于javascript - 第一次拖放 FileReader() 事件但无法读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223709/

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