Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

html - How to Create a Text File Locally at client side using JavaScript/JQuery

I wish to create a text file locally on my system using javascript/jquery.

I am trying this code, but not working on my system.

Machine : Ubuntu 10.4 Chrome : 14.0.835.126

window.webkitRequestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
        fs.root.getFile('~/Desktop/test.txt', {create: true}, function(fileEntry) {
            alert(fileEntry.fullPath);   //getting filepath
        }, function() {});
    }, function() {});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a little tricky but working

chrome.browserAction.onClicked.addListener(createFile);
createFile();

function createFile()
{
    chrome.tabs.getSelected(null, function(tab) {
        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("
");
                    builder.append("Saxena");

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

                    fileWriter.onwriteend = function() {
                        chrome.tabs.create({"url":fileEntry.toURL(),"selected":true},function(tab){});
                    };
                    fileWriter.write(blob);
                }, errorHandler);
            }, errorHandler);
        }, errorHandler);
    });
}
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);
}

Because of the Security Exceptions, i cannot create/modify a file on Local System. But in this code, I am actually creating a file in a directory which is allocated for Google Chrome Temporary Files and then downloading that file into my Downloads Folder.

This is the code of the popup page of a Chrome Extension.

:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...