Search code examples
javascripthtmlfileapi

FileWriter API: use blob to write data


i have a blob url like blob:blahblah that points to a file. I want to write the file behind this blob to local filesystem. The writer.write() documentation says it accepts a file object (from input-type-file) and a blob. But it throws a type mismatch error when try this

fileEntry.createWriter(function(writer) {
    writer.write(blob); //blob is a var with the value set to the blob url

i know the problem is that the blob does not get accepted but i would like to know how can i store a blob to the filesystem. i created the said blob earlier in the script from input-type-file and stored it's value in a var.

EDIT

Ok so i think i should have given more code in the first place.

first i create a blob url and store it in a var like this

files[i]['blob'] = window.webkitURL.createObjectURL(files[i]);

files is from an input-type-file html tag and i is looped for number of files. you know the gig.

then the variable goes through a number of mediums, first through chrome's message passing api to another page and then from that page to a worker via postMessage and then finally back to the parent page via postMessage again.

on the final page i intend to use it to store the blob's file to local file system via file system api like this..

//loop code
fileSystem.root.getFile(files[i]['name'], {create: true}, function(fileEntry) {
    fileEntry.createWriter(function(writer) {
        writer.write(files[i]['blob']);
    });
});
//loop code

but the writer.write throws Uncaught Error: TYPE_MISMATCH_ERR: DOM File Exception 11

i believe this error is because the variable supplied to writer.write is a text and not a blob object from something like createObjectUrl (directly and not after passing through multiple pages/scopes) or not a window.WebKitBlobBuilder. So how can a blob's url be used to store a file?


Solution

  • From your edited code snippet and description, it sounds like you're writing the blobURL to the filesystem rather than the File itself (e.g. files[i]['name'] is a URL). Instead, pass around the File object between main page -> other page -> worker -> main page. As of recent (in Chrome at least), your round trip is now possible. File objects can be passed to window.postMessage(), whereas before, the browser serialized the argument into a string.

    You 'fashion' a handler/reference to a Blob with createObjectURL(). There's not really a way to go from blobURL back to a Blob. So in short, no need to create createObjectURL(). Just pass around files[i] directly.