How to read/write local files through a web page?
Asked Answered
H

4

15

I am writing a html based app, and want to store and retrieve data from local file. This app will not be hosted on a web server.

Can anyone please help enlighten the topic on how can this be done?

Hydrophilic answered 19/8, 2012 at 2:53 Comment(1)
Many provide reference to the HTML5 File API but as far as I know, this API is not designed to read a pre-determined path and file name but rather must be selected via a file picker dialog. Not convenient for most. Just though I would provide that context to save you some time.Turpentine
D
4

You should use FileSystem API of HTML5:

window.requestFileSystem(window.TEMPORARY, 5*1024*1024, function(){
    fs.root.getFile('test.dat', {}, function(fileEntry) {
        fileEntry.file(function(file) {
            // Here is our file object ... 
        });
    });
}, errorHandler);

Checkout FileSystem API for more reference

Visit The HTML5 Test to test browser support

Doings answered 19/8, 2012 at 2:56 Comment(2)
Now the method should be prefixed webkitRequestFileSystem - developer.mozilla.org/en-US/docs/Web/API/Window/…Sandell
@Sandell webkitRequestFileSystem seems to be obsolete: it's a non-standard feature that is only supported in Chrome.Froe
E
3

Try HTML 5 FileSystem API

Below links has details

http://dev.w3.org/2009/dap/file-system/pub/FileSystem/

http://www.html5rocks.com/en/tutorials/file/filesystem/

Emad answered 19/8, 2012 at 8:51 Comment(2)
html5rocks.com is blocked here, can you provide an example?, i used proxy, but it is the same, the web page didn't open :(Strangeness
in general, answers should include more than just links - meta.stackexchange.com/a/8259Damar
M
2

The answer to this question depends on your answers to the following questions:

  • Are you fine with the fact that support for writing files currently exists only in Chromium-based browsers (Chrome & Opera)?
  • Are you fine with utilizing an as-of-now proprietary API to take advantage of such a capbility?
  • Are you fine with the possibility of removal of said API in the future?
  • Are you fine with the constriction of files created with said API to a sandbox (a location outside of which the files can produce no effect) on disk?
  • Are you fine with the use of a virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) to represent such files?

If you answered "yes" to all of the above, then with the File, FileWriter and FileSystem APIs, you can write files from the context of a browser tab/window using Javascript.

How, you asked?

BakedGoods*

Write file:

bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

Read file:

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs

Write file:

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Read file:

function onQuotaRequestSuccess(grantedQuota)
{

    function getfile(directoryEntry)
    {

        function readFile(fileEntry)
        {

            function read(file)
            {
                var fileReader = new FileReader();

                fileReader.onload = function(){var fileData = fileReader.result};
                fileReader.readAsText(file);             
            }

            fileEntry.file(read);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: false},
            readFile
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

But what if you answered "no" to any of the questions at the beginning?

If you are open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest through IsolatedStorage. However, managed code is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.

Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :

//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem", "silverlight"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

*BakedGoods is maintained by none other than this guy right here :)

Mesotron answered 7/7, 2016 at 1:2 Comment(0)
P
0

IF (and only if) you're platform will be IE you can leverage the HTA (HTML Applications) framework:

http://msdn.microsoft.com/en-us/library/ms536471(VS.85).aspx

Applications using this are granted system-level privledges and can use the same objects as Windows Scripting host (for example the file system object to read and access local files).

I've used it successfuly in the past for small workgroup applications and liked it - but this was in an IE-only corporate environment.

Photolithography answered 19/8, 2012 at 3:3 Comment(3)
Why not to use FileSystem API which works in all modern browsers?Doings
To repeat: If (and only if) your platform will be IE - as is still the case for a great majority of corporate environments.Photolithography
Sorry my platform is chrome based.Hydrophilic

© 2022 - 2024 — McMap. All rights reserved.