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

China☆狼群 提交于 2019-12-01 02:56:17

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

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.

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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!