Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

7. Cordova文件操作和IO

$
0
0

前言

这里学完了基本就告一段落了,文件操作按照原生来说,是需要一定权限的,这里就直接在root目录进行操作,存储位置位于内置app包名目录下。

这里代码已经写好了,今天要转java去写后台了,估计没时间写文档了,直接贴代码吧

构建

  • 安装插件
    cordova plugin add cordova-plugin-file

HTML代码

<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
    <meta name="format-detection" content="telephone=no">
    <meta charset="utf-8" />
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>

<div class="app">
<h1>文件操作</h1>
    <div id="deviceready" class="blink">
        <p class="event listening">Connecting to Device</p>
        <p class="event received">Device is Ready</p>
    </div>
<button id = "createFile"></button>
<button id = "writeFile"></button>
<button id = "readFile"></button>
<button id = "removeFile"></button>
<button id="nextPage">NEXT PAGE</button>
<textarea id = "textarea"></textarea>
</div>


<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/file_manager.js"></script>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>

</body>
</html>

JS代码

var app = {

    initialize: function () {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function () {
        var datas=null;
        var filePath = "";
        var fileName = "";

        this.receivedEvent('deviceready');

        document.getElementById("createFile").addEventListener("click", createFile);
        document.getElementById("writeFile").addEventListener("click", writeFile);
        document.getElementById("readFile").addEventListener("click", readFile);
        document.getElementById("removeFile").addEventListener("click", removeFile);
        document.getElementById("nextPage").addEventListener("click", nextPage);

        function createFile() {
            //设置类型 [TEMPORARY , PERSISTENT]
            var type = window.TEMPORARY;
            //设置大小
            var size = 5 * 1024 * 1024;
            //请求文件系统 ,参数直接看下面
            window.requestFileSystem(type, size, successCallback, errorCallback)
            //创建一个hello.txt文件,存到到根目录
            function successCallback(fs) {
                fs.root.getFile('hello.txt', {create: true, exclusive: true}, function (fileEntry) {
                    console.log('successfull!')
                }, errorCallback);
            }

            function errorCallback(error) {
                alert("未创建成功:" + error)
            }

        }


        function writeFile() {
            var type = window.TEMPORARY;
            var size = 5 * 1024 * 1024;

            window.requestFileSystem(type, size, successCallback, errorCallback)

            function successCallback(fs) {

                fs.root.getFile('hello.txt', {create: true}, function (fileEntry) {
                    //在本FileEntry中创建一个和文件关联的FileWriter方法
                    fileEntry.createWriter(function (fileWriter) {
                        fileWriter.onwriteend = function (e) {
                            alert("写入成功!");
                        };

                        fileWriter.onerror = function (e) {
                            alert("写入失败:" + e.toString());
                        };
                        //获取文本框中的值
                        var blob = new Blob([$(document).ready(function () {
                            $("#textarea").val();
                        })], {type: 'text/plain'});
                        //想文件中写数据
                        fileWriter.write(blob);
                    }, errorCallback);

                }, errorCallback);

            }

            function errorCallback(error) {
                alert("ERROR: " + error.code)
            }

        }

        function readFile() {
            var type = window.TEMPORARY;
            var size = 5 * 1024 * 1024;

            window.requestFileSystem(type, size, successCallback, errorCallback)

            function successCallback(fs) {

                fs.root.getFile('hello.txt', {}, function (fileEntry) {

                    fileEntry.file(function (file) {
                        //创建文件输入流
                        var reader = new FileReader();
                        //读完数据赋值给文本域
                        reader.onloadend = function (e) {
                            var txtArea = document.getElementById('textarea');
                            txtArea.value = this.result;
                        };
                        //从关联文件中读数据
                        reader.readAsText(file);

                    }, errorCallback);

                }, errorCallback);
            }

            function errorCallback(error) {
                alert("ERROR: " + error.code)
            }

        }

        function removeFile() {
            var type = window.TEMPORARY;
            var size = 5 * 1024 * 1024;

            window.requestFileSystem(type, size, successCallback, errorCallback)

            function successCallback(fs) {
                fs.root.getFile('hello.txt', {create: false}, function (fileEntry) {

                    fileEntry.remove(function () {
                        alert('File removed.');
                    }, errorCallback);

                }, errorCallback);
            }

            function errorCallback(error) {
                alert("ERROR: " + error.code)
            }

        }

        function nextPage() {
            location.href = "callActivity.html";
        }

    },


    // Update DOM on a Received Event
    receivedEvent: function (id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }

};

app.initialize();

JS代码的另一种简单模式,点击下一页之后的js代码



    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        // Now safe to use device APIs
        alert("设备准备就绪,给你看个空页面!");
    }
作者:lftaoyuan 发表于2017/5/25 18:03:36 原文链接
阅读:82 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>