本文介绍了使用HTML5 FileWriter truncate()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试HTML5文件API,我需要使用一个我不太了解的方法(因为它几乎没有在任何地方记录)。

I'm experimenting with the HTML5 File API, and I'm needing to use a method which I don't know enough about (simply because it's hardly documented anywhere).

我在谈论FileWriter truncate()方法,我知道它可以做我需要做的事情。基本上,不是将文本附加到某些文件数据或使用seek()来覆盖某个部分,我想用其他东西覆盖所有数据(例如从somedata覆盖到)。

I'm talking about the FileWriter truncate() method, and I know it does what I need to do. Basically, rather than appending text to some file data or using seek() to overwrite a certain portion, I want to overwrite all of the data with something else (e.g. from "somedata" to "").

以下是HTML5Rocks中的FileWriter设置片段,其中添加了truncate()。

Here's a snippet of the FileWriter setup from HTML5Rocks, with truncate() added in.

function onInitFs(fs) {

  fs.root.getFile('log.txt', {create: false}, function(fileEntry) {

    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {

      fileWriter.seek(fileWriter.length); // Start write position at EOF.
      fileWriter.truncate(1);

      // Create a new Blob and write it to log.txt.
      var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
      bb.append('Hello World');
      fileWriter.write(bb.getBlob('text/plain'));

    }, errorHandler);

  }, errorHandler);

}

window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler);

当调用writer.truncate()时,调用writer.write()会抛出文件异常错误。我相信这是因为readyState设置为WRITING。不幸的是,我不知道该如何解决这个问题。

When it gets to calling writer.truncate(), calling writer.write() throws a File Exception error. I believe this is because the readyState is set to WRITING. Unfortunately, I don't know how to get around that.

我已经尝试过查看就此而言,但它并没有告诉我任何关于truncate()方法的事情(虽然我知道它存在于Webkit JS控制台告诉我的内容中。

I've already tried looking through the HTML5Rocks section on this, but it doesn't tell me anything about a truncate() method (although I know it exists from what the Webkit JS Console tells me).

长话短说,我怎样才能正确使用truncate()方法而不会出错?

Long story short, how I can I use the truncate() method correctly without getting an error?

推荐答案

这样的事情可能会更加重要:

Something like this might be a little more to the point:



fileEntry.createWriter(function(fileWriter) {
    var truncated = false;
    fileWriter.onwriteend = function(e) {
        if (!truncated) {
            truncated = true;
            this.truncate(this.position);
            return;
        }
        console.log('Write completed.');
    };
    fileWriter.onerror = function(e) {
        console.log('Write failed: ' + e.toString());
    };
    var blob = new Blob(['helo'], {type: 'plain/text'});
    fileWriter.write(blob);
}, errorHandler);

这篇关于使用HTML5 FileWriter truncate()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 21:19