Create a File Using JavaScript in Chrome on Client Side

Create a file using Javascript in Chrome on client side

Sure you can, using the brand new APIs.

 window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

window.requestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
fs.root.getFile('test.bin', {create: true}, function(fileEntry) { // test.bin is filename
fileEntry.createWriter(function(fileWriter) {
var arr = new Uint8Array(3); // data length

arr[0] = 97; // byte data; these are codes for 'abc'
arr[1] = 98;
arr[2] = 99;

var blob = new Blob([arr]);

fileWriter.addEventListener("writeend", function() {
// navigate to file, will download
location.href = fileEntry.toURL();
}, false);

fileWriter.write(blob);
}, function() {});
}, function() {});
}, function() {});

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

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.

:)

Is it possible to write data to file using only JavaScript?

Some suggestions for this -

  1. If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
  2. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. Using the HTML5 API for Local Storage.

How to create a file in memory for user to download, but not through server?

You can use data URIs. Browser support varies; see Wikipedia. Example:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser.

For CSV, you can use:

<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>

Try the jsFiddle demo.

Client side file creation and download

you have no way to touch the local disk with Javascript by design.

I think you could pass the whole bunch of data from javascript to the server side code ( php, asp.net, java... ) then you could stream it down to the browser somehow.

Open, create files and save data in client side and reuse that data

You're right that localstorage is not enabled for Chrome packaged apps. However, depending on what kind of data you're managing, there are two APIs that should work.

chrome.storage.local is a general key-value store that will save data on the local machine (chrome.storage.sync is an identical API that will also synchronize the data between a users' devices, but I wouldn't recommend it for large files)

The API is simple to use:

chrome.storage.local.set({myKey: "myValue"}, function() {
if (!chrome.runtime.lastError) {
console.log("The value has been stored!");
} else {
console.error("There was an error!");
}
});

chrome.storage.local.get("myKey", function(data) {
if (!chrome.runtime.lastError) {
console.log("The value is " + data.myKey);
} else {
console.error("There was an error!");
}
});

(If you're using chrome.storage.sync, then you probably also want to add a listener to the chrome.storage.onChanged event, to know when data was changed from another location)

The other way may be what you're thinking of as "plain javascript file IO" -- the W3C File System API is supported by packaged apps. You can request storage space from the user and store actual files that you can read and write in JavaScript. There's a good introduction to it here.

Saving data to a local file using only JavaScript

You can use the Chrome Apps File API, you will need to grant access to the file via a user action once, but after that you can get access the file again by using restoreEntry



Related Topics



Leave a reply



Submit