使用 JavaScript 访问本地文件

发布于 2024-07-09 16:51:24 字数 235 浏览 12 评论 0原文

是否有使用 JavaScript 完成的本地文件操作? 我正在寻找一种无需安装即可完成的解决方案,例如需要 Adobe AIR

具体来说,我想从一个文件中读取内容并将这些内容写入另一个文件。 此时,我并不担心获得权限,只是假设我已经拥有这些文件的完全权限。

Is there local file manipulation that's been done with JavaScript? I'm looking for a solution that can be accomplished with no install footprint like requiring Adobe AIR.

Specifically, I'd like to read the contents from a file and write those contents to another file. At this point I'm not worried about gaining permissions and am just assuming I already have full permissions to these files.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

夜吻♂芭芘 2024-07-16 16:51:24

HTML5 功能的更新位于 http://www.html5rocks.com/en /tutorials/file/dndfiles/。 这篇优秀的文章将详细解释 JavaScript 中的本地文件访问。 上述文章的摘要:

该规范提供了多个接口,用于从“本地”文件系统访问文件

  1. 文件——单个文件; 提供只读信息,例如名称、文件大小、MIME 类型以及对文件句柄的引用。
  2. FileList - File 对象的类似数组的序列。 (想想 或从桌面拖动文件目录)。
  3. Blob - 允许将文件分割为字节范围。

请参阅下面 Paul D. Waite 的评论。

Just an update of the HTML5 features is in http://www.html5rocks.com/en/tutorials/file/dndfiles/. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:

The specification provides several interfaces for accessing files from a 'local' filesystem:

  1. File - an individual file; provides readonly information such as name, file size, MIME type, and a reference to the file handle.
  2. FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  3. Blob - Allows for slicing a file into byte ranges.

See Paul D. Waite's comment below.

终遇你 2024-07-16 16:51:24

如果用户通过 选择文件,您可以读取并使用处理该文件文件 API

设计不允许读取或写入任意文件。 这是对沙箱的侵犯。 来自 维基百科 -> JavaScript -> 安全性

JavaScript 和 DOM 提供了
恶意作者的可能性
交付在客户端上运行的脚本
计算机通过网络。 浏览器作者
使用两个来遏制这种风险
限制。 首先,脚本运行在
他们只能在沙箱中执行
与网络相关的操作,而不是
通用编程任务,例如
创建文件

2016 更新:可以通过 文件系统 API仅受 Chrome 和 Opera 支持可能最终不会被其他浏览器实现(使用 Edge 例外)。 有关详细信息,请参阅凯文的回答

If the user selects a file via <input type="file">, you can read and process that file using the File API.

Reading or writing arbitrary files is not allowed by design. It's a violation of the sandbox. From Wikipedia -> Javascript -> Security:

JavaScript and the DOM provide the
potential for malicious authors to
deliver scripts to run on a client
computer via the web. Browser authors
contain this risk using two
restrictions. First, scripts run in a
sandbox in which they can only perform
web-related actions, not
general-purpose programming tasks like
creating files.

2016 UPDATE: Accessing the filesystem directly is possible via the Filesystem API, which is only supported by Chrome and Opera and may end up not being implemented by other browsers (with the exception of Edge). For details see Kevin's answer.

别靠近我心 2024-07-16 16:51:24

如前所述,文件系统文件 API,以及 FileWriter API,可用于从浏览器选项卡/窗口上下文向客户端计算机读取和写入文件。

有几件与 FileSystem 和 FileWriter API 相关的事情您应该注意,其中一些已经提到,但值得重复:

  • API 的实现目前仅存在于基于 Chromium 的浏览器(Chrome 和 Opera)
  • 中API 已于 2014 年 4 月 24 日从 W3C 标准轨道中删除,并且截至目前是专有的。
  • 将来有可能从实现浏览器中删除(现在专有的)API。
  • 沙箱(一个位置)磁盘上的文件不能产生任何效果)用于存储使用 API 创建的文件
  • 虚拟文件系统(一种目录结构,不一定以与实际存在的形式相同的形式存在于磁盘上)当从浏览器中访问时)用于表示使用 API 创建的文件

以下是如何直接和间接使用 API 来执行这些操作的简单示例:

BakedGoods*

写入文件:

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

读取文件:

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

使用原始文件、FileWriter 和 FileSystem 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);

读取文件:

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

尽管 FileSystem 和 FileWriter API 不再处于标准轨道上,但在我看来,在某些情况下它们的使用是合理的,因为:

  • 未实现的浏览器供应商重新产生的兴趣可能会使它们重新回到标准轨道上
  • 实现的市场渗透(基于 Chromium 的)浏览器的使用率很高
  • Google(Chromium 的主要贡献者)尚未给出 API 的终止日期。

但是,“某些情况”是否包含您自己的情况,则由您决定。

*BakedGoods 的维护者不是别人,正是这里的这个人:)

As previously mentioned, the FileSystem and File APIs, along with the FileWriter API, can be used to read and write files from the context of a browser tab/window to a client machine.

There are several things pertaining to the FileSystem and FileWriter APIs which you should be aware of, some of which were mentioned, but are worth repeating:

  • Implementations of the APIs currently exist only in Chromium-based browsers (Chrome & Opera)
  • Both of the APIs were taken off of the W3C standards track on April 24, 2014, and as of now are proprietary
  • Removal of the (now proprietary) APIs from implementing browsers in the future is a possibility
  • A sandbox (a location on disk outside of which files can produce no effect) is used to store the files created with the APIs
  • 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) is used represent the files created with the APIs

Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:

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

Though the FileSystem and FileWriter APIs are no longer on the standards track, their use can be justified in some cases, in my opinion, because:

  • Renewed interest from the un-implementing browser vendors may place them right back on it
  • Market penetration of implementing (Chromium-based) browsers is high
  • Google (the main contributer to Chromium) has not given and end-of-life date to the APIs

Whether "some cases" encompasses your own, however, is for you to decide.

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

你在看孤独的风景 2024-07-16 16:51:24

更新 自 Firefox 17 起,此功能已被删除(请参阅 https:// /bugzilla.mozilla.org/show_bug.cgi?id=546848)。


在 Firefox 上,您(程序员)可以在 JavaScript 文件中执行此操作:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

并且系统将提示您(浏览器用户)允许访问。 (对于 Firefox,您只需在每次启动浏览器时执行一次)

如果浏览器用户是其他人,则必须授予权限。

UPDATE This feature is removed since Firefox 17 (see https://bugzilla.mozilla.org/show_bug.cgi?id=546848).


On Firefox you (the programmer) can do this from within a JavaScript file:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

and you (the browser user) will be prompted to allow access. (for Firefox you just need to do this once every time the browser is started)

If the browser user is someone else, they have to grant permission.

小巷里的女流氓 2024-07-16 16:51:24

NW.js 允许您使用 Javascript 创建桌面应用程序,而无需通常对浏览器施加的所有安全限制。 因此,您可以使用函数运行可执行文件,或创建/编辑/读取/写入/删除文件。 您可以访问硬件,例如当前的CPU使用率或正在使用的总RAM等。

您可以使用它创建不需要任何安装的Windows、Linux或Mac桌面应用程序。

NW.js allows you to create desktop applications using Javascript without all the security restrictions usually placed on the browser. So you can run executables with a function, or create/edit/read/write/delete files. You can access the hardware, such as current CPU usage or total ram in use, etc.

You can create a windows, linux, or mac desktop application with it that doesn't require any installation.

梦中的蝴蝶 2024-07-16 16:51:24

如果您在 Windows 上进行部署,Windows 脚本宿主 提供了非常好的对文件系统和其他本地资源有用的 JScript API。 然而,将 WSH 脚本合并到本地 Web 应用程序中可能并不像您希望的那么优雅。

If you're deploying on Windows, the Windows Script Host offers a very useful JScript API to the file system and other local resources. Incorporating WSH scripts into a local web application may not be as elegant as you might wish, however.

本宫微胖 2024-07-16 16:51:24

如果您有输入字段,例如

<input type="file" id="file" name="file" onchange="add(event)"/>

You can get to file content in BLOB format:

function add(event){
  var userFile = document.getElementById('file');
  userFile.src = URL.createObjectURL(event.target.files[0]);
  var data = userFile.src;
}

If you have input field like

<input type="file" id="file" name="file" onchange="add(event)"/>

You can get to file content in BLOB format:

function add(event){
  var userFile = document.getElementById('file');
  userFile.src = URL.createObjectURL(event.target.files[0]);
  var data = userFile.src;
}
自控 2024-07-16 16:51:24

FSO.js 封装了由 W3C 标准化的新 HTML5 FileSystem API,并提供了极其简单的 em> 读取、写入或遍历本地沙盒文件系统的方式。 它是异步的,因此文件 I/O 不会干扰用户体验。 :)

FSO.js wraps the new HTML5 FileSystem API that's being standardized by the W3C and provides an extremely easy way to read from, write to, or traverse a local sandboxed file system. It's asynchronous, so file I/O will not interfere with user experience. :)

柠檬 2024-07-16 16:51:24

如果您需要访问客户端上的整个文件系统、读/写文件、监视文件夹的更改、启动应用程序、加密或签署文档等,请查看 JSFS。

它允许从您的网页安全且无限制地访问客户端上的计算机资源,而无需使用 AcitveX 或 Java Applet 等浏览器插件技术。 然而,还必须安装一些软件。

为了使用 JSFS,您应该具备 Java 和 Java EE 开发 (Servlet) 的基本知识。

请在此处找到 JSFS:https://github.com/jsfsproject/jsfs。 它是免费的并根据 GPL 授权

If you need access to the entire file system on the client, read/write files, watch folders for changes, start applications, encrypt or sign documents, etc. please have a look at JSFS.

It allows secure and unlimited access from your web page to computer resources on the client without using a browser plugin technology like AcitveX or Java Applet. However, a peace of software has to be installed too.

In order to work with JSFS you should have basic knowledge in Java and Java EE development (Servlets).

Please find JSFS here: https://github.com/jsfsproject/jsfs. It's free and licensed under GPL

孤独患者 2024-07-16 16:51:24

有一个(商业)产品“localFS”,可用于在客户端计算机上读取和写入整个文件系统。

必须安装小型 Windows 应用程序,并在页面中包含小型 .js 文件。

作为一项安全功能,文件系统访问可以仅限于一个文件夹并使用密钥进行保护。

https://www.fathsoft.com/localfs

There is a (commercial) product, "localFS" which can be used to read and write entire file-system on client computer.

Small Windows app must be installed and tiny .js file included in your page.

As a security feature, file-system access can be limited to one folder and protected with a secret-key.

https://www.fathsoft.com/localfs

梦里南柯 2024-07-16 16:51:24

假设 JavaScript 代码可能需要的任何文件都应由用户直接允许。 著名浏览器的创建者通常不允许 JavaScript 访问文件。

该解决方案的主要思想是:JavaScript 代码无法通过本地 URL 来访问该文件。
但它可以通过拥有 DataURL 来使用该文件:因此,如果用户浏览文件并打开它,JavaScript 应该直接从 HTML 获取“DataURL”,而不是获取“URL”。

然后,它使用 readAsDataURL 函数和 FileReader 对象将 DataURL 转换为文件。
源代码和更完整的指南以及一个很好的示例位于:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader

Assuming that any file that JavaScript code might need, should be allowed directly by the user. Creators of famous browsers do not let JavaScript access files generally.

The main idea of the solution is: the JavaScript code cannot access the file by having its local URL.
But it can use the file by having its DataURL: so if the user browses a file and opens it, JavaScript should get the "DataURL" directly from HTML instead of getting "URL".

Then it turns the DataURL into a file, using the readAsDataURL function and FileReader object.
Source and a more complete guide with a nice example are in:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader

要走干脆点 2024-07-16 16:51:24

我只是提到这一点,因为没有人提到这一点。 据我所知,没有任何编程语言可以操纵底层文件系统。 所有编程语言都依赖操作系统中断来实际完成这些事情。 在浏览器中运行的 JavaScript 仅具有浏览器“中断”,通常不会授予文件系统访问权限,除非浏览器已实现支持此类中断。

也就是说,使用 JavaScript 访问文件系统的明显方法是使用 Node.js,它具有直接与底层操作系统交互的能力。

I am only mentioning this as no one mentioned this. There's no programming language I am aware of which allows manipulation of the underlying filesystem. All programming languages rely on OS interrupts to actually get these things done. JavaScript that runs in the browser only has browser "interrupts" to work with which generally does not grant filesystem access unless the browser has been implemented to support such interrupts.

This being said the obvious way to have file system access using JavaScript is to use Node.js which does have the capability of interacting with the underlying OS directly.

誰認得朕 2024-07-16 16:51:24

您必须使用 Javascript

window.showSaveFilePicker 中的新文件系统 API - 它允许我们将文件保存到用户计算机,然后我们可以对其进行读/写访问。

window.showOpenFilePicker - 它允许我们打开用户计算机上的现有文件,然后我们可以读取/写入该文件。

window.showDirectoryPicker - 它使我们能够访问目录,然后我们可以对其进行读/写。

查看教程 https://fjolt.com/article/javascript-new-file -系统API

You have to work with the new file system API in Javascript

window.showSaveFilePicker - which allows us to save a file to a users computer, which we then have read/write access to.

window.showOpenFilePicker - which allows us to open an existing file on a users computer, which we can then read/write to.

window.showDirectoryPicker - which gives us access to a directory, which we can then read/write to.

check tutorial at https://fjolt.com/article/javascript-new-file-system-api

黄昏下泛黄的笔记 2024-07-16 16:51:24

如果你使用的是 angularjs & aspnet/mvc,要检索 json 文件,您
必须在 Web 配置中允许 MIME 类型

<staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
  </staticContent>

if you are using angularjs & aspnet/mvc, to retrieve json files, you
have to allow mime type at web config

<staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
  </staticContent>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文