来自JavaScript FileReader的Access元素(Access element from JavaScript FileReader)

编程入门 行业动态 更新时间:2024-10-23 05:33:26
来自JavaScript FileReader的Access元素(Access element from JavaScript FileReader)

我正在尝试使用文件API在JavaScript中读取文件。

我有以下代码

function handleFileSelect(evt) { var files = evt.target.files; // FileList object var fileBlobs = []; var reader = new FileReader(); for (var i = 0, f; f = files[i]; i++) { fileBlobs.push(reader.readAsBinaryString(f)); console.log(reader) } }

它记录了我这个对象

FileReader {onloadend: null, onerror: null, onabort: null, onload: null, onprogress: null…} error: null onabort: null onerror: null onload: null onloadend: null onloadstart: null onprogress: null readyState: 2 result: "lat, lng, popup↵13.47262306516617336, 52.47896324136591062, 55↵13.40861762468653673, 52.54336741663770027, 44↵13.29255442595013115, 52.51117712705399754, 33↵13.38642907198692988, 52.44880630287082113, 22" __proto__: FileReader

我怎样才能访问result部分?

I am trying to read a file with in JavaScript with the File APIs.

I have the following code

function handleFileSelect(evt) { var files = evt.target.files; // FileList object var fileBlobs = []; var reader = new FileReader(); for (var i = 0, f; f = files[i]; i++) { fileBlobs.push(reader.readAsBinaryString(f)); console.log(reader) } }

It logs me this object

FileReader {onloadend: null, onerror: null, onabort: null, onload: null, onprogress: null…} error: null onabort: null onerror: null onload: null onloadend: null onloadstart: null onprogress: null readyState: 2 result: "lat, lng, popup↵13.47262306516617336, 52.47896324136591062, 55↵13.40861762468653673, 52.54336741663770027, 44↵13.29255442595013115, 52.51117712705399754, 33↵13.38642907198692988, 52.44880630287082113, 22" __proto__: FileReader

How can I access only the result part?

最满意答案

您需要处理FileReader的load事件。 在处理程序中,访问reader.result或this.result :

reader.onload = function() { var contents = this.result; };

读取文件是一种异步操作。 因此,您需要为每个文件创建单独的FileReader 。 如果要重用相同的FileReader ,则不能使用for循环。 相反,您必须等待读取下一个文件,直到处理完当前文件。

You need to handle the load event of the FileReader. In the handler, access reader.result or this.result:

reader.onload = function() { var contents = this.result; };

Reading the files is an asynchronous operation. So, you need to create a separate FileReader for each file. If you want to reuse the same FileReader, you can't use a for loop. Instead, you must wait to read the next file until after the current file is processed.

更多推荐

本文发布于:2023-07-26 15:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277527.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   FileReader   JavaScript   element   Access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!