Javascript 如何通过网页读/写本地文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12023858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:55:26  来源:igfitidea点击:

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

javascripthtmllocal-storageread-write

提问by praneybehl

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.

我正在编写一个基于 html 的应用程序,并希望从本地文件中存储和检索数据。此应用程序不会托管在 Web 服务器上。

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

任何人都可以帮助启发关于如何做到这一点的主题吗?

回答by Daniil Ryzhkov

You should use FileSystem API of HTML5:

您应该使用 HTML5 的 FileSystem API:

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 APIfor more reference

结帐FileSystem API以获取更多参考

Visit The HTML5 Testto test browser support

访问HTML5 测试以测试浏览器支持

回答by Kevin

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?
  • 您是否同意目前仅在基于 Chromium 的浏览器(Chrome 和 Opera)中支持写入文件的事实?
  • 您是否可以使用截至目前的专有 API 来利用这种能力?
  • 将来是否有可能删除上述 API?
  • 您是否可以将使用所述 API 创建的文件压缩到磁盘上的沙箱(文件无法产生任何影响的位置)?
  • 您是否可以使用虚拟文件系统(一种目录结构,它不一定以与从浏览器中访问时的形式相同的形式存在于磁盘上)来表示此类文件?

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

如果您对以上所有回答“是”,那么通过FileFileWriterFileSystemAPI,您可以使用 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

使用原始 File、FileWriter 和 FileSystem API

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 codeis required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.

如果您对非本机解决方案持开放态度,Silverlight 还允许通过IndependentStorage从选项卡/窗口竞赛中进行文件输入/输出。但是,使用此功能需要托管代码;需要编写此类代码的解决方案超出了本问题的范围。

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

当然,一个使用互补托管代码的解决方案,只留下一个 Javascript 来编写,完全在这个问题的范围内;):

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

* BakedGoods 是由这里的这个人维护的 :)

回答by Jim Davis

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

如果(并且仅当)您的平台是 IE,您可以利用 HTA(HTML 应用程序)框架:

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

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

使用它的应用程序被授予系统级特权,并且可以使用与 Windows 脚本主机相同的对象(例如,文件系统对象来读取和访问本地文件)。

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

我过去曾成功地将它用于小型工作组应用程序并喜欢它 - 但这是在仅 IE 的公司环境中。