简体   繁体   中英

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() {});

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("\n");
                    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.

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM