我正在使用 Phonegap 下载存档,解压缩它,然后读取文件。在我尝试以文本形式读取文件之前,一切都正常。如果我使用 readAsDataURL() ,那么我会得到一大堆记录到控制台的内容。
function( file ) {
console.log(file);
var reader = new FileReader();
reader.onloadend = function( evt ) {
console.log( evt.target.result );
};
reader.readAsDataURL( file );
}
如果我使用readAsText()
,我会得到null
。文件范围从 300KB 到 1.4MB,但所有文件在控制台中都返回 null
。
reader.readAsText( file );
为什么一个函数会返回一些值,而另一个函数会返回 null?它可以读取的文本大小有限制吗?
这是我在创建 reader
之前记录的 file
对象,我正在将函数应用到该对象(我已缩短了文件名):
{
"name":"categories.json",
"fullPath":"/var/mobile/.../Documents/data/file.json",
"type":null,
"lastModifiedDate":1380535318000,
"size":382456
}
这是 readAsText()
的 evt 对象:
{
"type":"loadend",
"bubbles":false,
"cancelBubble":false,
"cancelable":false,
"lengthComputable":false,
"loaded":0,
"total":0,
"target":{
"fileName":"/var/mobile/.../Documents/data/file.json",
"readyState":2,
"result":"null",
"error":null,
"onloadstart":null,
"onprogress":null,
"onload":null,
"onerror":null,
"onabort":null
}
}
更新:我在 W3C 文件 API 规范中看到,如果发生错误,结果只会设置为 null。但我尝试添加一个 reader.onerror()
函数,但没有被调用。
If an error occurs during reading the blob parameter, set readyState to DONE and set result to null. Proceed to the error steps.
最佳答案
您可能正在获取 fileEntry 而不是 fileObject。假设 file 实际上是 fileEntry,请尝试以下操作:
var
fileEntry = file, //for example clarity - assumes file from OP's file param
reader = new FileReader()
;
fileEntry.file( doSomethingWithFileObject );//gets the fileObject passed to it
function doSomethingWithFileObject(fileObject){
reader.onloadend = function(e){
doSomething(e.target.result); //assumes doSomething defined elsewhere
}
var fileAsText = reader.readAsText(fileObject);
}
绝对是一个极力减少繁琐的 API。
关于javascript - Phonegap FileReader readAsText 返回 null 但 readAsDataURL 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119829/