简体   繁体   English

如何使用javascript读取与html位于同一目录中的本地文件

[英]How to read local file that in located in the same directory as html using javascript

I have an application that creates html files that containes a lot of data to draw. 我有一个应用程序,它创建的HTML文件包含很多要绘制的数据。 This files are alwayes browsed from local file system (no http protocol at all). 始终从本地文件系统浏览此文件(根本没有http协议)。

I have an idea to compress the data and than place it in a raw format in a separate .dat file that will be put in the same place as .html one. 我有一个压缩数据的想法,然后将其以原始格式放在单独的.dat文件中,该文件将与.html放在同一位置。

It is not a problem to read and uncompress this .dat file when it is on a web server. 在Web服务器上读取和解压缩此.dat文件不是问题。 But I don't now how to read it when both files .html and .dat are local. 但是,当.html和.dat文件都是本地文件时,我现在不怎么读它。

Of course one can use browser file objects for it but in this case user will be alwayes asked to do a stupid action like to chose the the only file from an control. 当然,可以为它使用浏览器文件对象,但是在这种情况下,总是会要求用户执行一个愚蠢的操作,例如从控件中选择唯一的文件。

But I don't now how to read it when both files .html and .dat are local. 但是,当.html和.dat文件都是本地文件时,我现在不怎么读它。

I take it you mean from JavaScript within that HTML file. 我认为您是指该HTML文件中的JavaScript。 Depending on the browser, you can't except via the File API (which, as you've observed, requires that you have the user select the file in an input[type=file] element). 根据浏览器的不同,您只能通过File API进行操作 (如您所见, File API要求用户让用户在input[type=file]元素中选择文件)。

The way you'd want to do this would be via ajax ( XMLHttpRequest ), and that would work in some browsers, but not in others. 执行此操作的方法是通过ajax( XMLHttpRequest ),它在某些浏览器中有效,但在其他浏览器中无效。 Chrome, for instance, denies all attempts to use ajax with file:// URLs (eg, in pages served from the file system), even from local pages, even when you're using a relative URL like thefile.dat . 例如,Chrome拒绝所有尝试使用file:// URL(例如,在文件系统提供的页面中)使用ajax的尝试,即使是在本地页面中,即使您使用的是相对URL,例如thefile.dat IE allows it (or at least, older versions of IE did; I haven't tried it lately). IE允许它(或者至少是IE的较早版本允许;我最近没有尝试过)。

So unfortunately, I think the only way you can do this is via the File API, with the attendant input[type=file] . 因此,不幸的是,我认为您可以执行此操作的唯一方法是通过File API以及附带的input[type=file]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM