HTML5 File API: get File object within FileReader callback

后端 未结 2 1262
猫巷女王i
猫巷女王i 2020-12-14 19:25

With the new File API in Javascript you can read files in Javascript to create dataURLs to show clientside pictures clientside. I\'m wondering if you can reach the File obje

相关标签:
2条回答
  • 2020-12-14 20:08

    I already found a way. Maybe not better than the scope wrapper, but I think it's neater:

    for ( var i=0; i<files.length; i++ ) {
        var file = files[i]; // this is the file I want!!
        var filereader = new FileReader();
        filereader.file = file;
        filereader.onload = function(e) {
            var file = this.file; // there it is!
            // do stuff
        }
    }
    

    There is now a much easier (apparently faster) way (sync!) to get a file's data URL:

    img.src = URL.createObjectURL(file);
    

    Demo on http://jsfiddle.net/rudiedirkx/ZWMRd/8/show/ of both methods, and the original problem illustrated (drag multiple images and check the title tooltips).

    0 讨论(0)
  • 2020-12-14 20:11

    I don't think this.file is still supported. When I try to run the answer code, this.file is undefined whereas if I run the code from the question I get the expected results. I think you have to use the closure (at least this is how they do it on html5rocks (Example)).

    0 讨论(0)
提交回复
热议问题