html5 added js achieve read and write local files and obtain local file path

HTML5 provides an API to read and write can be achieved file, the file is read using the API is FileReader

code show as below:

Read local files

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

</head>
<body>
    <div>
        <input type="file" id="files" style="display: none" onchange="fileImport();">
        <input type="button" id="fileImport" value="导入">
    </div>
    <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>

Write to file

With the corresponding HTML5 FileReader also has a FileWriter , FileReader can be Chrome, FF and Safari are supported. It requires a certain version of the above. But it seems that only FileWriter supported Chrome.

code show as below:

//首先导入一个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)
});

Reading a local file path code

In obtaining the file path encountered some problems, due to security reasons, the new version of the browser do not support direct access to a local URL, the Internet to find some method, as follows:

<!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>
<div id="text" style="color:#f00;"></div>
<input type="file" id="file" onchange="getvl(this)" />

</body>
</html>

Codes are normally used in the above IE 6 7 8, at IE9, document.selection.createRange () to deny access, improved safety opinion.

Finally test found that in IE9, if the file control has the focus, the document.selection.createRange () denies access,

Therefore, only in obj.select () back plus a obj.blur () can be.

else if(Sys.ie>="7.0"){
  //ie7,ie8
  obj.select();
  obj.blur();
  file_url = document.selection.createRange().text;
 }
 
 
// obj = document.getElementById("file"); 
Published 17 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_36547601/article/details/79675948