HTML5 File API中的FileReader.readAsText如何工作? [英] How FileReader.readAsText in HTML5 File API works?
问题描述
我写了以下代码,以检查上传的文件是否存在与使用HTML5文件API。
< input type =fileid =myfile>< button type =buttononclick =addDoc()>添加文档< / button>< p id = DisplayText>< / p>
代码已被映射到如下:
function addDoc(){
var file = document.getElementById MYFILE)文件[0]。 // for input type = file
var reader = new FileReader();
reader.onload = function(e){}
reader.readAsText(file);
var error = reader.error;
var texte = reader.result;
document.getElementById(DisplayText)。innerText = reader.result; / *< p id =DisplayText> * /
}
浏览文件后从本地系统我试图删除浏览文件形式的文件夹,然后点击 addDoc()
。点击按钮后,我仍然可以看到 Filereader .result
不为空,可以显示所有内容。
有人可以解释 Filereader 的工作原理吗?一旦文件被浏览,文件读取器是否被绑定?
我们还可以检查系统是否只读 em>属性与 FileReader 类似于Java File.canread()
?
可以有人建议这个?我有IE11来测试代码。
FileReader
加载
事件以异步方式设置 .result
值要访问 .result
使用
加载
或加载
事件。
当文件一直存在时在< input type =file>
选择文件
或浏览.. 。
UI,在本地文件系统中删除文件不应该在 FileList
返回的文件
通过 .files
调用。请参阅 2.9.2。可传输对象, 6.7.3 DataTransfer界面。
每个
Blob
必须具有内部 快照状态 ,其中
必须最初设置为底层存储的状态,如果任何
这样的底层存储存在,并且必须通过
结构化克隆
。快照状态的进一步规范定义
可以找到文件
s。
2.9.8 Monkey patch for Blob和FileList对象
这个猴子补丁将在适当的时候被删除。请参阅 w3c / FileAPI
issue 32 。
Blob
对象是可克隆对象
。
每个
Blob
对象的[[a href =https://html.spec.whatwg.org/multipage/infrastructure.html#clone =nofollow noreferrer>克隆
]]内部方法,给定targetRealm并忽略内存,必须执行以下步骤:
如果这是
closed
,然后抛出一个DataCloneError
DOMException
。
在 targetRealm 中返回这个的新实例,对应于
相同的底层数据。
每个
FileList
对象的[[Clone]]
内部方法,给定
targetRealm 和内存,必须执行以下步骤:
让输出成为 targetRealm 中的新
FileList
对象。
对于 中的每个文件,添加?
[StructuredClone] [15](_ file,targetRealm,memory _)
到文件
对象
的输出。
返回输出。
在webkit和firefox浏览器中选择只读文件或文件夹
如果在本地文件系统中为文件设置了只读权限,则chrome为chrome,而用户在< input type =file>
元素中选择文件,其中 FileReader
用于读取文件,在 FileReader
中抛出错误,从 FileReader
progress
event。
如果一个 Blob URL
设置为相同的文件对象, blob:
URL将不会将请求时的只读文件返回给 Blob网址
。
r文件夹权限设置为只读
Chrome,铬
在chrome,铬,其中 webkitdirectory
属性被设置,文件夹被设置为只读权限 FileList
.length
event.target.files
返回 0
; event.target.files.webkitGetAsEntry()
未调用,未选择文件
呈现在< input type =file>
shadowDOM
。当文件夹在< input type =file>
或 droppable
属性集的元素中删除时,只读文件夹的目录 .name
和 .path
显示在 drop
event.dataTransfer
。
当用户在< textarea>
元素中删除文件或文件夹时,其中no drop
事件被附加 beforeunload
事件被调用,并在UI显示一个prompr $ /
你想离开这个网站吗?
您所做的更改可能无法保存。
<停留><离开> //< buttons>
Firefox
在具有 allowdirs
属性的firefox版本47.0b9设置为< input type =file>
元素,用户点击选择文件夹..
< input>
,文件夹父文件夹的.name
和 .path
可以在 .then()
链接到 event.target.getFilesAndDirectories()
。当递归迭代目录
条目时,不会返回选定文件夹中包含的文件或文件夹。返回一个空字符串。
如果用户点击选择文件...
< input>
,并选择一个文件夹,而不设置只读权限,当文件管理器中的文件夹被单击时,列出文件夹中的文件。
如果在设置了只读权限的情况下选择了一个文件夹,则在UI显示时会呈现通知( alert()
无法读取<目录名称>的内容
权限被拒绝
,安全问题
* nix OS
当用户将< textarea>
元素,其中没有 drop
事件被附加,用户文件系统的文件夹的完整路径文件:
协议被暴露。文件夹中包含的文件的路径也不会设置为 .value
;例如,
file:/// home / user / Documents / Document /
当文件在< textarea>
元素中删除时,不在 drop
事件被附加,用户文件系统的文件的完整路径被设置为 .value
; textarea的>
;也就是说,
file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue.txt
如果在< textarea>
元素中选择并删除多个文件,所有的完整文件路径都设置为 .value
< textarea>
,由新行字符 \\\
file:/// home / user / Documents /Document/MyFileFullPathDisplayedAtTextAreaValue1.txt
file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue2.txt
..
其中 XMLHttpRequest()
是为文件路径创建的,错误记录在控制台
NS_ERROR_DOM_BAD_URI:访问限制的URI被拒绝
/ pre>
设置为
.src
的< img>
元素与.crossOrigin
设置为anonymous
img
错误
事件处理程序调用
调用
window.open()
在第一个参数设置完整路径错误:访问文件:/// home / user /文件/文件/ MyFileFullPathDisplayedAtTextAreaValue.png脚本被拒绝
规范
4.10.5.1.18 。文件上传状态(
type = file
)
出于历史原因,
值
IDL属性使用字符串C:\fakepath\
前缀
文件名。一些传统用户代理
实际上包含完整路径(这是一个安全漏洞)。
因此,以向下兼容的方式从值
IDL
属性获取文件名是不重要的。
strong> filename
在获取时,它必须返回字符串C:\fakepath\,后面是第一个在
列表中选择的文件
(如果有的话),如果列表为空,则为空字符串。在
文件
设置中,如果新值为空字符串,则必须将所选文件
的列表
清空;否则,它必须抛出InvalidStateError
DOMException
。
注意:这个fakepath要求是一个悲伤的历史事故。请参阅文件上传
注意由于
路径组件
不允许在所选文件列表中的文件名中
,\fakepath\
不能错误的
作为路径组件。
4.10.5.1.18。文件上传状态(
type = file
)
路径组件< h2>
当一个
< input>
元素type
属性位于文件上传
状态,本节中的规则适用。
< input>
元素表示
列出所选文件
,
每个文件由文件名,文件类型和文件体组成(文件的
内容)。
文件名不能包含
路径组件
即使在
用户已经从不同的目录中选择了一个完整的目录层次结构或多个
的文件同名的情况下。 路径组件,对于文件上传
状态的
目的,是文件名
的那些部分,由U + 005C REVERSE SOLIDUS character()characters。
错误报告 https://bugzilla.mozilla.org/show_bug.cgi?id=1311823
将文件放在< textarea>在数据URI
以下评论由 Neal Deakin 的错误报告
我认为所提到的步骤是:
- 打开数据:text / html,
- 将文件从桌面拖动到textarea
我可以在Linux上重现这个,但不能在Windows或Mac上复制。
上面的提示是正确的; Linux将数据作为网址和
明文包含。
删除文件
数据:
prototcol数据URI
在firefox和chrome,chrome数据:text / html的,< TextArea>< / textarea的>
Firefox
文件或文件夹设置为
.value
< textarea>
。
Chrome,铬
将文件放在
数据URI
只有textarea
元素在chrome,铬替换数据URI
与删除的文件路径在地址栏,并加载删除的文件在同一个选项卡,替换数据URI
与删除的文件的内容。
plnkr http://plnkr.co/edit/ZfAGEAiyLLq8rGXD2ShE?p=preview
html
,javascript
重现上述问题<!DOCTYPE html>
< html>
< head>
< style>
body {
height:400px;
}
textarea {
width:95%;
height:inherit;
}
< / style>
< script>
window.onload = function(){
var button = document.querySelector(#myfile + button);
var input = document.getElementById(myfile);
var display = document.getElementById(DisplayText);
var text = null;
函数readFullPathToFileOnUserFileSystem(e){
var path = e.target.value;
console.log(path);
var w = window.open(path,_blank);
var img = new Image;
img.crossOrigin =anonymous;
img.onload = function(){
document.body.appendChild(this);
}
img.onerror = function(err){
console.log(img error,err.message)
}
img.src = path;
var request = new XMLHttpRequest();
request.open(GET,path.trim(),true);
request.onload = function(){
console.log(this.responseText)
}
request.error = function(err){
console.log err.message)
}
request.send();
}
display.addEventListener(input,readFullPathToFileOnUserFileSystem);
input.addEventListener(change,addDoc);
input.addEventListener(progress,function(event){
console.log(progress,event)
});
button.addEventListener(click,handleText)
函数addDoc(event){
var mozResult = [];
函数mozReadDirectories(条目,路径){
console.log(dir,entries,path);
return [] .reduce.call(entries,function(promise,entry){
return promise.then(function(){
console.log(entry,entry);
return Promise.resolve(entry.getFilesAndDirectories()|| entry)
.then(function(dir){
console.log(dir getFilesAndDirectories,dir)
return dir
})
})
},Promise.resolve())
.catch(function(err){
console.log(err,err.message)
})
.then(function(items){
console.log(items,items);
var dir = items.filter(function(folder){
返回文件夹instanceof目录
});
var files = items.filter(function(file){
return file instanceof File
});
if (文件。长度){
console.log(files:,files,path);
mozResult = mozResult.concat.apply(mozResult,files);
}
if(dir.length){
console.log(dir,dir [0] instanceof Directory,dir [0]);
return mozReadDirectories(dir,dir [0] .path || path);
} else {
if(!dir.length){
return Promise.resolve(mozResult).then(function(complete){
返回完成
})
}
}
})
.catch(function(err){
console。 log(err)
})
};
console.log(files,event.target.files);
if(getFilesAndDirectoriesin event.target){
return(event.type ===drop?event.dataTransfer:event.target)
.getFilesAndDirectories()
.then(function(dir){
if(dir [0] instanceof Directory){
console.log(dir)
return mozReadDirectories(dir,dir [0] .path ||路径)
.then(function(complete){
console.log(complete:,complete);
event.target.value = null;
});
} else {
if(dir [0] instanceof File&&dir [0] .size> 0){
return Promise.resolve(dir)
。 (function(complete){
console.log(complete:,complete);
})
} else {
if(dir [0] .size == 0 ){
throw new Error(无法处理''+ dir [0] .name +'目录+在firefox的drop事件,上传文件夹在选择文件夹...输入);
}
}
}
})catch(function(err){
console.log(err)
})
}
var reader = new FileReader();
reader.onload = function(e){
text = reader.result;
console.log(FileReader.result,text);
button.removeAttribute(disabled);
}
reader.onerror = function(err){
console.log(err,err.loaded,err.loaded === 0,file);
button.removeAttribute(disabled);
}
reader.onprogress = function(e){
console.log(e,e.lengthComputable,e.loaded,e.total);
}
reader.readAsArrayBuffer(file);
}
函数handleText(){
//从`addDoc`获取`text`:`reader.result`的东西
display.textContent = text;
button.setAttribute(disabled,disabled);
//如果不需要或再次引用,将`text`设置为'null'
text = null;
}
}
< / script>
< / head>
< body>
< input type =fileid =myfilewebkitdirectory目录allowdirs>
< button type =buttondisabled>添加文档< / button>
< br>
< br>
< textarea id =DisplayText>< / textarea>
< / body>
< / html>
plnkr http://plnkr.co/edit/8Ovw3IlYKI8BYsLhzV88?p=preview
您可以使用附加到
#myfile
元素的更改
事件来处理用户的文件选择操作。
替换
元素
< p>
元素显示来自.readAsText()
调用的load
事件的结果。
显示
.result
FileReader
点击
在按钮
元素,设置变量文本
到reader.result
加载
事件FileReader
在点击
事件在按钮
设置.textContent
#DisplayText
元素到变量引用以前设置reader.result
。
<!DOCTYPE html>< html> <风格> body {height:400px; } textarea {width:95%; height:inherit; }< / style>< head> <脚本> window.onload = function(){var button = document.querySelector(#myfile + button); var input = document.getElementById(myfile); var display = document.getElementById(DisplayText); var text = null; input.addEventListener(change,addDoc); button.addEventListener(click,handleText)function addDoc(event){var file = this.files [0] var reader = new FileReader(); reader.onload = function(e){text = reader.result; button.removeAttribute( 无效); } reader.onerror = function(err){console.log(err,err.loaded,err.loaded === 0,file); button.removeAttribute( 无效); } reader.readAsText(event.target.files [0]); } function handleText(){//使用`text`做的东西:`addDoc`的reader.result` display.textContent = text; button.setAttribute(disabled,disabled); //如果不需要或再次引用,将`text`设置为'null'text = null; }}< / script>< / head>< body> < input type =fileid =myfileaccept =text / *> < button type =buttondisabled>添加文档< / button>< br>< br> < textarea id =DisplayText>< / textarea>< / body>< / html>
I wrote the following code to check whether the uploaded file exists or not using HTML5 file API.
<input type="file" id="myfile"> <button type="button" onclick="addDoc()">Add Document</button> <p id="DisplayText"></p>
The following JavaScript code has been mapped to it is as follows:
function addDoc() { var file=document.getElementById("myFile").files[0]; //for input type=file var reader=new FileReader(); reader.onload = function(e) {} reader.readAsText(file); var error = reader.error; var texte=reader.result; document.getElementById("DisplayText").innerText=reader.result; /*<p id="DisplayText>*/ }
After browsing a file from local system I tried to delete the "browsed" document form the folder before clicking on
addDoc()
. After clicking the button I could still seeFilereader.result
is not null and could display all the content.Can someone explain on how the Filereader works? Is it that the FileReader gets bound as soon as the file is browsed?
Also can we check whether the system Readonly Attribute with FileReader similar to Java
File.canread()
?Could someone suggest on this? I have IE11 to test the code.
解决方案
FileReader
load
event sets the.result
value asynchronously. To access the.result
useload
orloadend
event.When a file has been selected at
<input type="file">
Choose File
orBrowse...
UI, deleting file at local filesystem should not effect theFile
object atFileList
returned by.files
call. See 2.9.2. Transferable objects, 6.7.3 The DataTransfer interface.4. The Blob Interface and Binary Data
Each
Blob
must have an internal snapshot state, which must be initially set to the state of the underlying storage, if any such underlying storage exists, and must be preserved throughstructured clone
. Further normative definition ofsnapshot state
can be found forFile
s.2.9.8 Monkey patch for Blob and FileList objects
This monkey patch will be removed in due course. See w3c/FileAPI issue 32.
Blob
objects arecloneable objects
.
Each
Blob
object's [[Clone
]] internal method, given targetRealm and ignoring memory, must run these steps:If this is
closed
, then throw a"DataCloneError"
DOMException
.Return a new instance of this in targetRealm, corresponding to the same underlying data.
FileList
objects are cloneable objects.Each
FileList
object's[[Clone]]
internal method, given targetRealm and memory, must run these steps:
Let output be a new
FileList
object in targetRealm.For each file in this, add ?
[StructuredClone][15](_file, targetRealm, memory_)
to the end of the list ofFile
objects of output.Return output.
Selecting read-only files or folders at webkit and firefox browsers
At chrome, chromium if read-only permission is set for file at local filesystem and user selects file at
<input type="file">
element, whereFileReader
is used to read file, an error is thrown atFileReader
, generated fromFileReader
progress
event.If a
Blob URL
is set to the same file object, theblob:
URL will not return the the read-only file at request to theBlob URL
.
Selection of folder where folder permission is set to read-only
Chrome, chromium
At chrome, chromium where
webkitdirectory
attribute is set and folder is selected with read-only permissionFileList
.length
ofevent.target.files
returned0
;event.target.files.webkitGetAsEntry()
is not called,"No file chosen"
is rendered at<input type="file">
shadowDOM
. When a folder is dropped at<input type="file">
or element wheredroppable
attribute set, the directory.name
and.path
of the read-only folder is displayed atdrop
event.dataTransfer
.When user drops file or folder at
<textarea>
element, where nodrop
event is attachedbeforeunload
event is called and a prompr is displayed at UIDo you want to leave this site? Changes you made may not be saved. <Stay><Leave> // <buttons>
Firefox
At firefox version 47.0b9 with
allowdirs
attribute is set at<input type="file">
element, where user clicks"Choose folder.."
<input>
, the folder.name
and.path
of the parent folder are accessible at.then()
chained toevent.target.getFilesAndDirectories()
. The files or folders contained within the selected folder are not returned when recursively iteratingDirectory
entries; an an empty string is returned.If user clicks
"Choose file..."
<input>
and a folder is selected without read-only permission set, when the folder at file manager is clicked, the files in the folder are listed.Where a folder is selected where read-only permission is set an
alert()
notification is rendered at UI displayingCould not read the contents of <directory name> Permission denied
Bug, security issue
*nix OS
When user drops folder at
<textarea>
element, where nodrop
event is attached, the full path to the folder at user filesystemfile:
protocol is exposed. The paths to the files contained within the folder are not also set as.value
; e.g.,"file:///home/user/Documents/Document/"
When a file is dropped at
<textarea>
element, where notdrop
event is attached, the full path to the file at user filesystem is set as.value
of<textarea>
; that is,"file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue.txt"
If multiple files are selected and dropped at
<textarea>
element, all of the full file paths are set as.value
of<textarea>
, delineated by new line character\n
"file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue1.txt" "file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue2.txt" ..
Where an
XMLHttpRequest()
is made for the file path and error is logged atconsole
NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
When set as
.src
of an<img>
element with.crossOrigin
set to"anonymous"
theimg
error
event handler is calledAt call to
window.open()
with full path set at first parameterError: Access to '"file:///home/user/Documents/Document/MyFileFullPathDisplayedAtTextAreaValue.png"' from script denied
Specification
4.10.5.1.18. File Upload state (
type=file
)For historical reasons, the
value
IDL attribute prefixes the file name with the string "C:\fakepath\
". Some legacy user agents actually included the full path (which was a security vulnerability). As a result of this, obtaining the file name from thevalue
IDL attribute in a backwards-compatible way is non-trivial.4.10.5.4. Common
<input>
element APIsfilename
On getting, it must return the string "C:\fakepath\" followed by the name of the first file in the list of
selected files
, if any, or the empty string if the list is empty. On setting, if the new value is the empty string, it must empty the list ofselected files
; otherwise, it must throw an "InvalidStateError
"DOMException
.NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
NOTE: Since
path components
are not permitted in file names in the list ofselected files
, the "\fakepath\
" cannot be mistaken for a path component.
4.10.5.1.18. File Upload state (
type=file
)
Path components
When an
<input>
element’stype
attribute is in theFile Upload
state, the rules in this section apply.The
<input>
elementrepresents
a list ofselected files
, each file consisting of a file name, a file type, and a file body (the contents of the file).File names must not contain
path components
, even in the case that a user has selected an entire directory hierarchy or multiple files with the same name from different directories. Path components, for the purposes of theFile Upload
state, are those parts of file names that are separated by U+005C REVERSE SOLIDUS character () characters.Bug report https://bugzilla.mozilla.org/show_bug.cgi?id=1311823
Dropping file at <textarea> at data URI
Following comment by Neal Deakin at bug report
I think the steps referred to are:
- Open data:text/html,
- Drag a file from the desktop to the textarea
I can reproduce this on Linux, but not on Windows or Mac.
The hunch above is correct; Linux is including the data as a url and plaintext as well.
dropped files at
data:
prototcoldata URI
at firefox, and chrome, chromiumdata:text/html,<textarea></textarea>
Firefox
The full path name of file or folder set as
.value
of<textarea>
.Chrome, chromium
Dropping file at
data URI
having onlytextarea
element at chrome, chromium replaces thedata URI
with dropped file path at address bar, and loads the dropped file at the same tab, replacing thedata URI
with the content of the dropped file.plnkr http://plnkr.co/edit/ZfAGEAiyLLq8rGXD2ShE?p=preview
html
,javascript
to reproduce issue described above<!DOCTYPE html> <html> <head> <style> body { height: 400px; } textarea { width: 95%; height: inherit; } </style> <script> window.onload = function() { var button = document.querySelector("#myfile + button"); var input = document.getElementById("myfile"); var display = document.getElementById("DisplayText"); var text = null; function readFullPathToFileOnUserFileSystem(e) { var path = e.target.value; console.log(path); var w = window.open(path, "_blank"); var img = new Image; img.crossOrigin = "anonymous"; img.onload = function() { document.body.appendChild(this); } img.onerror = function(err) { console.log("img error", err.message) } img.src = path; var request = new XMLHttpRequest(); request.open("GET", path.trim(), true); request.onload = function() { console.log(this.responseText) } request.error = function(err) { console.log(err.message) } request.send(); } display.addEventListener("input", readFullPathToFileOnUserFileSystem); input.addEventListener("change", addDoc); input.addEventListener("progress", function(event) { console.log("progress", event) }); button.addEventListener("click", handleText) function addDoc(event) { var mozResult = []; function mozReadDirectories(entries, path) { console.log("dir", entries, path); return [].reduce.call(entries, function(promise, entry) { return promise.then(function() { console.log("entry", entry); return Promise.resolve(entry.getFilesAndDirectories() || entry) .then(function(dir) { console.log("dir getFilesAndDirectories", dir) return dir }) }) }, Promise.resolve()) .catch(function(err) { console.log(err, err.message) }) .then(function(items) { console.log("items", items); var dir = items.filter(function(folder) { return folder instanceof Directory }); var files = items.filter(function(file) { return file instanceof File }); if (files.length) { console.log("files:", files, path); mozResult = mozResult.concat.apply(mozResult, files); } if (dir.length) { console.log(dir, dir[0] instanceof Directory, dir[0]); return mozReadDirectories(dir, dir[0].path || path); } else { if (!dir.length) { return Promise.resolve(mozResult).then(function(complete) { return complete }) } } }) .catch(function(err) { console.log(err) }) }; console.log("files", event.target.files); if ("getFilesAndDirectories" in event.target) { return (event.type === "drop" ? event.dataTransfer : event.target) .getFilesAndDirectories() .then(function(dir) { if (dir[0] instanceof Directory) { console.log(dir) return mozReadDirectories(dir, dir[0].path || path) .then(function(complete) { console.log("complete:", complete); event.target.value = null; }); } else { if (dir[0] instanceof File && dir[0].size > 0) { return Promise.resolve(dir) .then(function(complete) { console.log("complete:", complete); }) } else { if (dir[0].size == 0) { throw new Error("could not process '" + dir[0].name + "' directory" + " at drop event at firefox, upload folders at 'Choose folder...' input"); } } } }).catch(function(err) { console.log(err) }) } var reader = new FileReader(); reader.onload = function(e) { text = reader.result; console.log("FileReader.result", text); button.removeAttribute("disabled"); } reader.onerror = function(err) { console.log(err, err.loaded, err.loaded === 0, file); button.removeAttribute("disabled"); } reader.onprogress = function(e) { console.log(e, e.lengthComputable, e.loaded, e.total); } reader.readAsArrayBuffer(file); } function handleText() { // do stuff with `text`: `reader.result` from `addDoc` display.textContent = text; button.setAttribute("disabled", "disabled"); // set `text` to `null` if not needed or referenced again text = null; } } </script> </head> <body> <input type="file" id="myfile" webkitdirectory directory allowdirs> <button type="button" disabled>Add Document</button> <br> <br> <textarea id="DisplayText"></textarea> </body> </html>
plnkr http://plnkr.co/edit/8Ovw3IlYKI8BYsLhzV88?p=preview
You can use
change
event attached to#myfile
element to handle file selection action by user.Substitute
<textarea>
element for<p>
element to display result ofload
event from.readAsText()
call.To display
.result
ofFileReader
atclick
atbutton
element, set variabletext
toreader.result
withinload
event ofFileReader
atclick
event atbutton
set.textContent
of#DisplayText
element to variable referencing previously setreader.result
.<!DOCTYPE html> <html> <style> body { height: 400px; } textarea { width:95%; height: inherit; } </style> <head> <script> window.onload = function() { var button = document.querySelector("#myfile + button"); var input = document.getElementById("myfile"); var display = document.getElementById("DisplayText"); var text = null; input.addEventListener("change", addDoc); button.addEventListener("click", handleText) function addDoc(event) { var file = this.files[0] var reader = new FileReader(); reader.onload = function(e) { text = reader.result; button.removeAttribute("disabled"); } reader.onerror = function(err) { console.log(err, err.loaded , err.loaded === 0 , file); button.removeAttribute("disabled"); } reader.readAsText(event.target.files[0]); } function handleText() { // do stuff with `text`: `reader.result` from `addDoc` display.textContent = text; button.setAttribute("disabled", "disabled"); // set `text` to `null` if not needed or referenced again text = null; } } </script> </head> <body> <input type="file" id="myfile" accept="text/*"> <button type="button" disabled>Add Document</button><br><br> <textarea id="DisplayText"></textarea> </body> </html>
这篇关于HTML5 File API中的FileReader.readAsText如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!