Javascript 我可以用 HTML5/JS 编写文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4309958/
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 11:50:29  来源:igfitidea点击:

Can I write files with HTML5/JS?

javascripthtmlio

提问by Jiew Meng

I wonder if there is any way I can write to files from HTML5/JS? In the broswer ...

我想知道是否有任何方法可以从 HTML5/JS 写入文件?在浏览器...

采纳答案by mike

Yes, using the new FileWriter API.

是的,使用新的 FileWriter API。

http://www.w3.org/TR/file-writer-api/

http://www.w3.org/TR/file-writer-api/

You can see the current browser support here: http://caniuse.com/#feat=filesystem

您可以在此处查看当前的浏览器支持:http: //caniuse.com/#feat=filesystem

回答by ecmanaut

Assuming your end goal is to let the user save your file somewhere where they will find it, as when right-clicking a link and choosing "Save As...", there isn't wide browser coverage for those APIs yet, likely due to security considerations.

假设您的最终目标是让用户将您的文件保存在他们可以找到的地方,例如当右键单击链接并选择“另存为...”时,这些 API 还没有广泛的浏览器覆盖范围,可能是由于出于安全考虑。

What you can do, however – APIs or not – is cheesing it with a link to a data:uriwith a downloadattribute specifying your suggested filename. For instance:

但是,无论是否使用 API,您都可以做的是通过一个指向data:uri的链接来实现它,该uridownload属性指定了您建议的文件名。例如:

<a id="save" download="earth.txt" href="data:text/plain,mostly harmless&#10;">Save</a>

When clicked, at least in Chrome, this will save a file containing the text mostly harmless(and a trailing newline) as earth.txtin your download directory. To set the file contents from javascript instead, call this function first:

单击时,至少在 Chrome 中,这将保存一个包含文本mostly harmless(和尾随换行符)的文件,如earth.txt您的下载目录中一样。要从 javascript 设置文件内容,请先调用此函数:

function setSaveFile(contents, file_name, mime_type) {
  var a = document.getElementById('save');
  mime_type = mime_type || 'application/octet-stream'; // text/html, image/png, et c
  if (file_name) a.setAttribute('download', file_name);
  a.href = 'data:'+ mime_type +';base64,'+ btoa(contents || '');
}

回答by Pankaj Parashar

Yes it is possible to read & write files using HTML5+JS.

是的,可以使用 HTML5+JS 读取和写入文件。

Link to get you started - Exploring FileSystem API

帮助您入门的链接 - Exploring FileSystem API

I also wrote an article a while back for SpeckyBoy on the same topic that you might find useful - http://speckyboy.com/2012/10/30/getting-to-grips-with-the-html5-file-api-2/

不久前,我还为 SpeckyBoy 写了一篇关于您可能会觉得有用的同一主题的文章 - http://speckyboy.com/2012/10/30/getting-to-grips-with-the-html5-file-api- 2/

回答by Angus

As far as I know, you can't write to files from HTML5, because giving a web page access to the user's files would be a security risk.

据我所知,您不能从 HTML5 写入文件,因为让网页访问用户的文件会带来安全风险。

If you just need to store some data so your page can access it later, HTML5 does have something called Web Storage which can do that.

如果您只需要存储一些数据以便您的页面以后可以访问它,HTML5 确实有一种叫做 Web Storage 的东西可以做到这一点。

Or you could store the data in cookies (if it's very small) or on the server.

或者您可以将数据存储在 cookie(如果它非常小)或服务器上。

回答by Newclique

Another possibility is to consider creating something like a ClickOnce app in the Windows platform. This would present a link to a downloadable executable that would run in the user's OS but could make web-based callbacks to send and retrieve data. The ClickOnce app could embed a browser control and thus you would have both a web-compatible application with the ability to talk directly to the user's storage.

另一种可能性是考虑在 Windows 平台中创建类似 ClickOnce 应用程序的东西。这将提供一个指向可下载可执行文件的链接,该可执行文件将在用户的操作系统中运行,但可以进行基于 Web 的回调以发送和检索数据。ClickOnce 应用程序可以嵌入浏览器控件,因此您将拥有一个与 Web 兼容的应用程序,并且能够直接与用户的存储进行对话。

回答by Kevin

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

这个问题的答案取决于您对以下问题的回答:

  • Are you fine with the fact that support for such a capability 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?
  • 您是否同意目前仅在基于 Chromium 的浏览器(Chrome 和 Opera)中存在对此类功能的支持?
  • 您是否可以使用截至目前的专有 API 来利用这种能力?
  • 将来是否有可能删除上述 API?
  • 您是否可以将使用所述 API 创建的文件压缩到磁盘上的沙箱(文件无法产生任何影响的位置)?

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

如果您对上述所有问题的回答都是“是”,那么是的,使用FileWriterFileSystemAPI,您可以使用 Javascript 从浏览器选项卡/窗口的上下文中编写文件。

Here is a simple example of how the APIs are used in tandem to do this:

下面是一个简单的示例,说明如何协同使用 API 来执行此操作:

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

With BakedGoods*, a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native (including FileSystem), and some non-native storage facilities, the above is accomplished with this:

使用BakedGoods*,一个 Javascript 库,它建立了一个统一的接口,可用于在所有原生(包括 FileSystem)和一些非原生存储设施中进行常见的存储操作,上面是这样完成的:

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

The FileSystem spec defines no guidelines on how directory structures are to appear on disk. In Chromium-based browsers for example, the sandbox has 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), within which the directories and files created with the APIs are placed.

FileSystem 规范没有定义目录结构如何出现在磁盘上的指南。例如,在基于 Chromium 的浏览器中,沙箱有一个虚拟文件系统(一种目录结构,它不一定以与从浏览器中访问时相同的形式存在于磁盘上),其中使用已放置 API。

So though you may be able to write files to a system with the APIs, locating the files without the APIs (well, without the FileSystem API) could be a non-trivial affair.

因此,尽管您可以使用 API 将文件写入系统,但在没有 API(嗯,没有 FileSystem API)的情况下定位文件可能是一件非常重要的事情。

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

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