在 HTML5 中使用 FileReader 选择文件时出现问题
我正在尝试制作视频预览脚本。我想要一个用于拖放和由输入 type="file" 元素选择的文件的功能。这是函数:
function FileHandler(files){
for(var i = 0; i < files.length; i++){
file = files[i];
var reader = new FileReader();
reader.onload = function(evt){
var VideoSpan = document.createElement('span');
var Video = document.createElement('video');
VideoSpan.classList.add('VideoPreviewSpaner');
Video.classList.add('VideoPreview');
Video.controls="controls";
Video.src = evt.target.result
VideoSpan.appendChild(Video);
document.getElementById('VideoWindow').appendChild(VideoSpan);
document.getElementById('VideoWindow').style.display = "block";
}
reader.readAsDataURL(file);
}
}
然后是
<input type="file" id="OpenFileDialog" multiple onchange="FileHandler(this.files)">
dnd 处理程序:
function d(e){
e.stopPropagation();
e.preventDefault();
files = e.dataTransfer.files;
FileHandler(files);
}
document.getElementById('droparea').addEventListener('drop',d,false);
我真的看不出有什么问题 reader.onload 从未被调用!如果有一些帮助那就太好了!
Im trying to make a video preview script. I want one function for both drag and drop and files selected by an input type="file" element. Here is the function:
function FileHandler(files){
for(var i = 0; i < files.length; i++){
file = files[i];
var reader = new FileReader();
reader.onload = function(evt){
var VideoSpan = document.createElement('span');
var Video = document.createElement('video');
VideoSpan.classList.add('VideoPreviewSpaner');
Video.classList.add('VideoPreview');
Video.controls="controls";
Video.src = evt.target.result
VideoSpan.appendChild(Video);
document.getElementById('VideoWindow').appendChild(VideoSpan);
document.getElementById('VideoWindow').style.display = "block";
}
reader.readAsDataURL(file);
}
}
And then the
<input type="file" id="OpenFileDialog" multiple onchange="FileHandler(this.files)">
And the dnd handler:
function d(e){
e.stopPropagation();
e.preventDefault();
files = e.dataTransfer.files;
FileHandler(files);
}
document.getElementById('droparea').addEventListener('drop',d,false);
I really can't see whats wrong the reader.onload is never called! It would be great with some help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我遇到类似问题时来到这里。
尝试实现 onerror,您会发现 Google Chrome 抛出“安全错误”。不过,在 Firefox(7.0.1) 中也同样有效。
这是由于 Google Chrome 对开发人员施加的本地文件安全限制。这种本地文件安全限制确实对快速开发测试造成了影响!
将 HTML 放在网络服务器上,问题就解决了。没有网络服务器?尝试使用火狐浏览器!
--allow-file-access-from-files 选项对我来说从来没有真正起作用!
最好的,
斯里达尔
Got here when I faced similar issue.
Try to implement onerror and you will find Google Chrome throwing a "Security error". The same works in Firefox(7.0.1) though.
Its due to the local file security restriction Google Chrome has imposed upon the developers. This local files security restriction really takes a toll on quick dev-testings!
Put the HTML on a web-server, the issue is resolved. No web-server? try on Firefox!
--allow-file-access-from-files option never really worked for me!
Best,
Sridhar