7. Cordova文件操作和IO

前言

这里学完了基本就告一段落了,文件操作按照原生来说,是需要一定权限的,这里就直接在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("设备准备就绪,给你看个空页面!");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值