gpt4 book ai didi

javascript - event.target 和 getelementbyid 的区别

转载 作者:行者123 更新时间:2023-11-29 16:53:09 25 4
gpt4 key购买 nike

我正在使用 File API,我想知道 event.target.files[0]getElementbyId("demo").files[0]

后者似乎有效。上下文可能会有所帮助,下面的代码使用了 event.target.files[0] 的实例:

<!DOCTYPE html>
<html>
<head>
<title> Home Page </title>
</head>

<body>
<input type="file" id="file" name="file"/>
<output id="list"></output>

<p id="demo"></p>

<script>
function handleFileSelect(evt) {
// grab the file that was uploaded which is type File.
// evt is the event that was triggered
// evt.target returns the element that triggered the event
// evt.target.files[0] returns the file that was uploaded, type File
var file = evt.target.files[0];

//file is not of TYPE BLOB!!!

// instantiate a FileReader object to read/save the file that was uploaded
var reader = new FileReader();

// read the file and save as an array
arrayoffile=reader.readAsArrayBuffer(file);

document.getElementById("demo").innerHTML = arrayoffile.length;
window.alert("hello");

}

document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>

谢谢!

最佳答案

evt.target.files[0]document.getElementById('file').files[0] 中完全相同的对象handleFileSelect 处理程序。

问题是您使用的是 FileReader不正确。 readAsArrayBuffer只开始读取缓冲区。

The readAsArrayBuffer method is used to start reading the contents of a specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains an ArrayBuffer representing the file's data.

您需要附加事件处理程序 onload 和/或 onerror 以获得一些结果。看看下面:

function handleFileSelect(evt) {
var file = evt.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var arrayBuffer = event.target.result;
document.getElementById("demo").innerHTML = arrayBuffer.byteLength;
};
reader.readAsArrayBuffer(file);
}

document.getElementById('file').addEventListener('change', handleFileSelect, false);
<input type="file" id="file" name="file" />
<output id="list"></output>

<p id="demo"></p>

请注意 ArrayBuffer报价byteLength属性(property)。

关于javascript - event.target 和 getelementbyid 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34604998/

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