html5 fileReader - 如何只读取文件的前N个字符? [英] html5 fileReader -- how to only read the first N characters of a file?
本文介绍了html5 fileReader - 如何只读取文件的前N个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我使用如下图案来读取一系列文件的前3个字符:
Currently I use a pattern like the following to read the first 3 characters of a series of files:
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var fr = new FileReader();
fr.onload = function(e) {
var first_three_chars = e.target.result.substr(0,3);
}
fr.readAsText(f);
}
问题是我只对前3个字符感兴趣文件,而这个方法读取整个文件,浪费了大量的内存和时间。如何快速迭代文件,只需快速查看第一个字符?
The trouble is that I'm only interested in the first 3 characters of the file, whereas this method reads the entire file, wasting lots of memory and time. How can I quickly iterate over the files, simply taking quick peeks at the first characters?
编辑:slice()就是答案,谢谢sshen。我是这样做的:
slice() was the answer, thanks sshen. Here's how I did it:
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var fr = new FileReader();
fr.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) {
var first_three_chars = e.target.result;
}
};
var blob = f.slice(0, 3);
fr.readAsText(blob);
}
推荐答案
您可以使用 .slice
方法。您可以阅读更多此处
You can use the .slice
method. You can read more here
var reader = new FileReader();
reader.onloadend = function(evt)
{
if (evt.target.readyState == FileReader.DONE) // DONE == 2
{
alert(evt.target.result);
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
这篇关于html5 fileReader - 如何只读取文件的前N个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文