代码在jsFiddle上工作正常但在本地系统上没有

时间:2011-10-07 15:24:45

标签: javascript file-io google-chrome-extension

此代码在jsFiddle上运行正常但在我的系统上运行不正常。 JsFiddle

我已经从草稿中检查过(在jsFiddle上按Ctrl + Shift + Enter键),将此代码添加到head section&修改如下:

window.addEvent('load', function() {
    window.webkitRequestFileSystem(window.TEMPORARY, 2*1024*1024, function(fs) {
        fs.root.getFile('test', {create: true}, function(fileEntry) {
            alert(fileEntry.toURL());
            fileEntry.createWriter(function(fileWriter) {
                var builder = new WebKitBlobBuilder();
                builder.append("Saurabh");
                builder.append("\n");
                builder.append("Saxena");

                var blob = builder.getBlob('text/plain');

                fileWriter.onwriteend = function() {
                    // navigate to file, will download
                    location.href = fileEntry.toURL();
                };
                fileWriter.write(blob);
            }, function() {});
        }, function() {});
    }, function() {});
});

2 个答案:

答案 0 :(得分:4)

您获得FileError.SECURITY_ERR,因为您不允许在本地运行此代码。如果你没有空的错误处理程序,你会看到错误。

如果将以下代码保存到本地文件并在chrome中运行它,您将看到错误:

<html>
<script>
function doit() {

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}



window.webkitRequestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
        fs.root.getFile('test', {create: true}, function(fileEntry) {
            fileEntry.createWriter(function(fileWriter) {
                var builder = new WebKitBlobBuilder();
                builder.append("Saurabh");
                builder.append("\n");
                builder.append("Saxena");

                var blob = builder.getBlob('text/plain');

                fileWriter.onwriteend = function() {
                    // navigate to file, will download
                    location.href = fileEntry.toURL();
                };
                fileWriter.write(blob);
            }, errorHandler);
        }, errorHandler);
    }, errorHandler);
}
</script>

<body onload="doit();">

</body>
</html>

答案 1 :(得分:1)

  

在本地系统上

Google Chrome对file://有一些限制。您可以尝试使用--allow-file-access-from-files运行Chrome。也许它会有所帮助。否则,您需要将网页放在某个开发服务器上进行测试。