简体   繁体   English

html为本地时,如何使用JavaScript读取本地文件

[英]How can I use JavaScript to read a local file when the html is local

I would like to be able to read a file that is stored in the same directory as the html file. 我希望能够读取与html文件存储在同一目录中的文件。 When the html file is accessed by http, there is no problem; 当通过http访问html文件时,没有问题。 I can just use a HttpXMLRequest. 我可以只使用HttpXMLRequest。 However when the HTML is being read off the local disk (as with File/Open in most desktop browsers, it seems HttpXMLRequest does not work. I used to do this with a Java Applet, but (a) I've noticed that doesn't work with some browsers and (b) I'd like a solution that uses just JavaScript: no Java and no Flash. 但是,当从本地磁盘上读取HTML时(与大多数桌面浏览器中的File / Open一样,似乎HttpXMLRequest无法正常工作。我以前是使用Java Applet来完成此操作的,但是(a)我注意到这没有实现) (b)我想要一个仅使用JavaScript的解决方案:不使用Java,也不使用Flash。

HttpXMLRequest as it suggests makes HTTP requests - without a webserver, this isn't possible but it's not hard to setup a localhost server. HttpXMLRequest可以发出HTTP请求-没有Web服务器,这是不可能的,但是设置本地主机服务器并不困难。

Though I'm sure there are other opinionated people who will suggest otherwise; 尽管我敢肯定还有其他有思想的人会提出其他建议; my preference for a windows machine is EasyPHP http://www.easyphp.org/ and XAMP if you're not using the default/preinstalled apache server. 如果您未使用默认/预安装的apache服务器,我更喜欢Windows机器是EasyPHP http://www.easyphp.org/和XAMP。

Here is a solution for reading a file into javascript, but I am unclear at present if you are limited to only AJAX style requests. 这是一种将文件读入javascript的解决方案,但是目前还不清楚,如果您仅限于AJAX样式请求。 Anyway, if you are not limited to only that method then you could use FileReader . 无论如何,如果您不仅限于该方法,则可以使用FileReader

The following example uses readAsDataURL but you can use one of the other listed methods. 以下示例使用readAsDataURL,但您可以使用其他列出的方法之一。

void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

So here is the example that will load a file, then convert it to base64 and display the resulting string for you. 因此,以下示例将加载文件,然后将其转换为base64并为您显示结果字符串。

CSS 的CSS

#progress_bar {
    margin: 10px 0;
    padding: 3px;
    border: 1px solid #000;
    font-size: 14px;
    clear: both;
    opacity: 0;
    -moz-transition: opacity 1s linear;
    -o-transition: opacity 1s linear;
    -webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
    opacity: 1.0;
}
#progress_bar .percent {
    background-color: #99ccff;
    height: auto;
    width: 0;
}
#display {
    width: 500px;

height: 150px; 高度:150px; } }

HTML 的HTML

<input type="file" id="files" name="file" />
<button id="cancel">Cancel read</button>
<div id="progress_bar">
    <div class="percent">0%</div>
</div>
<div>Base64 encoded result</div>
<textarea id="display"></textarea>

Javascript Java脚本

/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */

(function () {
    "use strict";

    var reader,
    progress = document.querySelector(".percent"),
        display = document.getElementById("display"),
        iFiles = document.getElementById("files"),
        bCancel = document.getElementById("cancel"),
        dropZone = document.getElementById("drop_zone"),
        filebox = document.getElementById("filebox"),
        list = document.getElementById("list");

    function abortRead() {
        if (reader) {
            reader.abort();
        }
    }

    function errorHandler(evt) {
        switch (evt.target.error.code) {
            case evt.target.error.NOT_FOUND_ERR:
                alert("File Not Found!");
                break;
            case evt.target.error.NOT_READABLE_ERR:
                alert("File is not readable");
                break;
            case evt.target.error.ABORT_ERR:
                break; // noop
            default:
                alert("An error occurred reading this file.");
        };
    }

    function updateProgress(evt) {
        // evt is an ProgressEvent.
        if (evt.lengthComputable) {
            var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
            // Increase the progress bar length.
            if (percentLoaded < 100) {
                progress.style.width = percentLoaded + "%";
                progress.textContent = percentLoaded + "%";
            }
        }
    }

    function handleFileSelect(evt) {
        // Reset progress indicator on new file selection.
        progress.style.width = "0%";
        progress.textContent = "0%";

        reader = new FileReader();
        reader.onerror = errorHandler;
        reader.onprogress = updateProgress;
        reader.onabort = function (e) {
            alert('File read cancelled');
        };

        reader.onloadstart = function (e) {
            document.getElementById('progress_bar').className = 'loading';
        };

        reader.onload = function (e) {
            // Ensure that the progress bar displays 100% at the end.
            progress.style.width = "100%";
            progress.textContent = "100%";
            setTimeout("document.getElementById('progress_bar').className='';", 2000);
            display.value = e.target.result;
        }

        // Read in the image file as a binary string.
        reader.readAsDataURL(evt.target.files[0]);
    }

    iFiles.addEventListener("change", handleFileSelect, false);
    bCancel.addEventListener("click", abortRead, false);
}());

On jsfiddle jsfiddle上

Update: from the W3C File API - working draft 更新:从W3C File API-工作草案

Security Considerations 安全注意事项

This specification allows web content to read files from the underlying file system, as well as provides a means for files to be accessed by unique identifiers, and as such is subject to some security considerations. 该规范允许Web内容从底层文件系统读取文件,并提供一种通过唯一标识符访问文件的方式,因此要考虑到一些安全方面的考虑。 This specification also assumes that the primary user interaction is with the element of HTML forms [HTML], and that all files that are being read by FileReader objects have first been selected by the user. 本规范还假设主要的用户交互是与HTML表单[HTML]的元素进行交互,并且FileReader对象正在读取的所有文件都已由用户首先选择。 Important security considerations include preventing malicious file selection attacks (selection looping), preventing access to system-sensitive files, and guarding against modifications of files on disk after a selection has taken place. 重要的安全考虑因素包括:防止恶意文件选择攻击(选择循环),防止访问系统敏感文件,以及在选择发生后防止磁盘上文件的修改。

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

相关问题 当用户使用HTML5 File API按下按钮时,如何读取本地文件? - How can I read a local file when the user presses a button using the HTML5 File API ? 如何在javascript中从D盘读取本地文件 - How can i read local file from D drive in javascript 如何使用JavaScript从本地文件读取CSS规则 - How can i read CSS rule from local file with JavaScript 如何在 Javascript 中读取具有固定路径的本地文件? 我只有文件的位置作为字符串。 不允许使用 HTML 表单 - How can I read a local file with a fixed path in Javascript? I only have the location of the file as a string. NO HTML forms allowed 如何使用Javascript读取本地文本文件并逐行读取? - How to use Javascript to read local text file and read line by line? Javascript,如何读取本地文件? - Javascript, how to read local file? 如何使用javascript读取与html位于同一目录中的本地文件 - How to read local file that in located in the same directory as html using javascript 如何将本地文本文件读取到本地html并将内容读取到javascript的二维数组? - How to read a local text file to a local html and read the content to a two dimensional array for javascript? 使用HTML和Javascript读取本地纯文本文件 - Read local plain text file with HTML and Javascript 使用JavaScript从本地文件读取和修改HTML - Read and modify HTML from a local file with JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM