masoomeh
masoomeh

Reputation: 21

writing twice using filewriter api in html5 leads to error

I'm trying to use BlobBuilder and FileWriter API in HTML to write data to the file. My problem is that if I use write function twice, I get an error. The following code executes OK:

  var bb = new window.WebKitBlobBuilder();
  bb.append('LOREL');
  outWriter.write(bb.getBlob('text/plain'));

But if I change it as follows (try to write twice)

  var bb = new window.WebKitBlobBuilder();
  bb.append('LOREL');
  outWriter.write(bb.getBlob('text/plain'));
  bb.append('LOREL');
  outWriter.write(bb.getBlob('text/plain'));

I get an error. The error code is: INVALID_STATE_ERR

Any help would be appreciated.

Upvotes: 2

Views: 941

Answers (1)

ebidel
ebidel

Reputation: 24109

The issue is that FileWriter.write() is asynchronous and you're trying to write more data to the file before the first write has complete. According to the spec, a FileException should be thrown if readyState==WRITING. Likely what's happening in your case. You need something like:

var bb = new window.WebKitBlobBuilder();
bb.append('LOREL');

outWriter.onwrite = function(e) {
  bb.append('LOREL');
  outWriter.write(bb.getBlob('text/plain'));
};

outWriter.write(bb.getBlob('text/plain'));

Also, I hope your code snippet is just an example and you're not actually appending, writing, appending, writing. Otherwise, use one write():

var bb = new window.WebKitBlobBuilder();
bb.append('LOREL');
bb.append('LOREL');
outWriter.write(bb.getBlob('text/plain'));

Upvotes: 2

Related Questions