Dre*_*eur 27 html5 google-chrome filereader
有人能给我一个使用FileReader API的例子去获取chrome中文件的内容吗?
它似乎正在回归undefined我.
<!doctype html>
<html>
<script>
function handle_files(files) {
  console.log(files)
  reader = new FileReader()
  ret = []
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    text = reader.readAsText(file) //readAsdataURL
    console.log(text) //undefined
    ret.push(text)
  }
  console.log(ret) // [undefined]
}
</script>
<body>
FileReader Test
<input type="file" onchange="handle_files(this.files)">
</body>
</html>
Dre*_*eur 33
我的问题是我假设FileReader是同步的.这是正确的方法.如果您使用的是chrome,则此代码必须在服务器(localhost或站点)上运行.它不适用于本地文件.
<!doctype html>
<html>
<script>
function handle_files(files) {
  for (i = 0; i < files.length; i++) {
    file = files[i]
    console.log(file)
    var reader = new FileReader()
    ret = []
    reader.onload = function(e) {
      console.log(e.target.result)
    }
    reader.onerror = function(stuff) {
      console.log("error", stuff)
      console.log (stuff.getMessage())
    }
    reader.readAsText(file) //readAsdataURL
  }
}
</script>
<body>
FileReader that works!
<input type="file" multiple onchange="handle_files(this.files)">
</body>
</html>
Sam*_*son 18
File API FileReader对象在Chrome中的运行方式与FireFox,Opera或Internet Explorer 10中的运行方式相同(Yup,适用于IE).
首先声明读者的新实例:
var reader = new FileReader();
为各种事件定义回调:
reader.onloadend = function( ){
    document.body.style.backgroundImage = "url(" + this.result + ")";
}
然后传递一些东西来阅读:
reader.readAsDataURL( file );
小提琴:http://jsfiddle.net/jonathansampson/K3A9r/
当您处理多个文件时,情况会有所不同.虽然很明显我们需要遍历生成的FileList,但我们还需要使用闭包来防止文件数据被多次迭代篡改:
// Continue only if we have proper support
if ( window.FileReader ) {
  // Provide our logic upon the change even of our input
  document.getElementById("collection").onchange = function(){
    // Couple variables for handling each file
    var counter = -1, file;
    // Cycle over all files
    while ( file = this.files[ ++counter ] ) {
      // Create a reader for this particular file
      var reader = new FileReader();
      // Respond to the onloadend event of the reader
      reader.onloadend = (function(file){
        return function(){
          var image = new Image();
          image.height = 100;
          image.title = file.name;
          image.src = /^image/.test(file.type) ? this.result : "t9QlH.png";
          document.body.appendChild( image );
        }
      })(file);
      // Begin reading data for this file
      reader.readAsDataURL( file );
    }
  }
}?
小提琴:http://jsfiddle.net/jonathansampson/jPTV3/
虽然FileReader几乎适用于所有现代浏览器,但您仍然希望确保不会对旧浏览器上的用户造成任何骚扰.在使用FileReader之前,请务必检查窗口对象是否存在:
if ( window.FileReader ) {
    // Safe to use FileReader
}
我应该注意,在Chrome中的文件:///路径中运行此操作会导致体验中断.默认情况下,Chrome的当前版本不允许file:///页面访问其他文件.您可以使用--allow-file-access-from-files标记更改此行为加载Chrome .

请注意,此方法仅允许对打开的浏览器实例上的文件进行文件访问.如果您希望将来所有浏览器实例都适用,您可以从桌面修改快捷方式.只需右键单击Chrome快捷方式,然后转到属性即可.接下来,将标志添加到目标的末尾.
| 归档时间: | 
 | 
| 查看次数: | 35135 次 | 
| 最近记录: |