Table of Contents
代码如下:
读取本地文件
写入文件
读取本地文件路径代码
Home Web Front-end HTML Tutorial h5+js implements local file reading and writing

h5+js implements local file reading and writing

Mar 24, 2018 am 11:38 AM
file reading

这次给大家带来h5+js实现本地文件读取和写入,h5+js实现本地文件读取和写入的注意事项有哪些,下面就是实战案例,一起来看一下。

代码如下:

读取本地文件

<!doctype html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Document</title></head><body>
    <p>
        <input type="file" id="files" style="display: none" onchange="fileImport();">
        <input type="button" id="fileImport" value="导入">
    </p>
    <script src="../js/jQuery/jquery-1.11.1.js"></script>
    <script>
        //点击导入按钮,使files触发点击事件,然后完成读取文件的操作
        $("#fileImport").click(function () {
            $("#files").click();
        })        function fileImport() {            //获取读取我文件的File对象
            var selectedFile = document.getElementById('files').files[0];            var name = selectedFile.name;//读取选中文件的文件名
            var size = selectedFile.size;//读取选中文件的大小
            console.log("文件名:"+name+"大小:"+size);            var reader = new FileReader();//这是核心,读取操作就是由它完成.
            //reader.readAsText(selectedFile);//读取文件的内容,也可以读取文件的URL
            reader.onload = function () {                //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
                console.log(this.result);
            }
        }    </script></body></html>
Copy after login

写入文件

HTML5中与FileReader相对应的也有一个FileWriter,FileReader可以被Chrome、FF和Safari都支持。要求一定版本以上的。 但是FileWriter似乎只有被Chrome支持.

代码如下:

//首先导入一个Js文件<script type="text/javascript" src="./JS/FileSaver.js" charset="utf-8"></script>//HTML中添加一个导出元素<input type="button" id="export" value="导出"/>//JS文件$("#export).click(function(){
    var content = "这是直接使用HTML5进行导出的";
    var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "file.txt");//saveAs(blob,filename)
});
Copy after login

读取本地文件路径代码

在获取文件路径的遇到些问题,由于安全原因,新版的浏览器都不支持直接获取本地URL,在网上找了些方法,如下:

<!doctype html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Document</title></head><body><script type="text/javascript">
    //FX获取文件路径方法
    function readFileFirefox(fileBrowser) {        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        }        catch (e) {
            alert('无法访问本地文件,由于浏览器安全设置。为了克服这一点,请按照下列步骤操作:(1)在地址栏输入"about:config";(2) 右键点击并选择 New->Boolean; (3) 输入"signed.applets.codebase_principal_support" (不含引号)作为一个新的首选项的名称;(4) 点击OK并试着重新加载文件');            return;
        }        var fileName=fileBrowser.value; //这一步就能得到客户端完整路径。下面的是否判断的太复杂,还有下面得到ie的也很复杂。
        var file = Components.classes["@mozilla.org/file/local;1"]
            .createInstance(Components.interfaces.nsILocalFile);        try {            // Back slashes for windows
            file.initWithPath( fileName.replace(/\//g, "\\\\") );
        }        catch(e) {            if (e.result!=Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;
            alert("File '" + fileName + "' cannot be loaded: relative paths are not allowed. Please provide an absolute path to this file.");            return;
        }        if ( file.exists() == false ) {
            alert("File '" + fileName + "' not found.");            return;
        }        return file.path;
    }    //根据不同浏览器获取路径
    function getvl(obj){//判断浏览器
        var Sys = {};        var ua = navigator.userAgent.toLowerCase();        var s;
        (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
            (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                    (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;        var file_url="";        if(Sys.ie<="6.0"){            //ie5.5,ie6.0
            file_url = obj.value;
        }else if(Sys.ie>="7.0"){            //ie7,ie8
            obj.select();
            file_url = document.selection.createRange().text;
        }else if(Sys.firefox){            //fx
            //file_url = document.getElementById("file").files[0].getAsDataURL();//获取的路径为FF识别的加密字符串
            file_url = readFileFirefox(obj);
        }else if(Sys.chrome){
            file_url = obj.value;
        }        //alert(file_url);
        document.getElementById("text").innerHTML="获取文件域完整路径为:"+file_url;
    }</script><h1>JS获取文件域完整路径的方法,兼容不同浏览器</h1><p id="text" style="color:#f00;"></p><input type="file" id="file" onchange="getvl(this)" /></body></html>
Copy after login

以上代码在IE 6 7 8均正常使用,在IE9下,document.selection.createRange()拒绝访问,看来安全性有所提高。

最后测试发现,在IE9下,如果file控件获得焦点,则document.selection.createRange()拒绝访问,

因此,只需要在obj.select()后面加一句obj.blur()即可。

else if(Sys.ie>="7.0"){  //ie7,ie8
  obj.select();
  obj.blur();
  file_url = document.selection.createRange().text;
 } 
 
// obj = document.getElementById("file");
Copy after login

The above is the detailed content of h5+js implements local file reading and writing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles