cocos creator 实现文件读写功能 网页版本(一)

使用该方法,可以便于通过creator做些关卡编辑,生成数据,等操作

功能尚未整理完全,会慢慢加入:

网页版:

/** 
 * 文件操作
 * 点击按钮进行操作
 * 
 */
import FileMgr from "./FileMgr";

const {ccclass, property} = cc._decorator;

// import fs from `./fs`;

@ccclass
export default class WriteFile extends cc.Component {

    // LIFE-CYCLE CALLBACKS:
    @property(cc.Node)
    NodeScore : cc.Node = null;

    @property(String)    
    PathName : string = "";

    onLoad () {
        // jsb.fileUtils.writeStringToFile()
    }

    start () {

    }

    /**
     * 打开文件选择器+读取数据
     *
     * @memberof WriteFile
     */
    openLocalFile(){
        // 打开文件选择器
        FileMgr.getInstance().openLocalFile(null,(file)=>{
            console.log("file",file)
            // 读取数据
            FileMgr.getInstance().readLocalFile(file,1,(result)=>{
                console.log("file result",result)
            })

        });
    }

    /**
     * 保存数据到文件
     *
     * @memberof WriteFile
     */
    SaveFile(){
        let children =  this.NodeScore.children;
        let list = []
        for (let index = 0; index < children.length; index++) {
                let data = {
                    position : cc.v2(0,0),
                    scoreType : "",
                    scoreNum : 0,
                }
                let comp = children[index].getComponent("ScoreNode");
                data.scoreType = comp.ScoreType;
                data.scoreNum = comp.ScoreNum;
                data.position =  children[index].position;
                list.push(data);
        }

        FileMgr.getInstance().saveForBrowser(JSON.stringify(list),`json/${this.PathName}.json`);
    }

    // update (dt) {}
}
/** 文件操作管理类 */

// 读取文件方式
enum READ_FILE_TYPE {
    DATA_URL,// readAsDataURL, base64
    TEXT,// readAsText
    BINARY,// readAsBinaryString
    ARRAYBUFFER,// readAsArrayBuffer
}

export default class FileMgr{
    private static instance : FileMgr;
    public static getInstance(): FileMgr{
        if(!FileMgr.instance){
            FileMgr.instance = new FileMgr();
        }
        return FileMgr.instance;
    }

    /**
     * 打开文件选择器
     *
     * @param {string} accept
     * @param {(file: File) => void} callback
     * @memberof FileMgr
     */
    openLocalFile(accept: string, callback: (file: File) => void) {
        let inputEl: HTMLInputElement = document.getElementById('file_input');
        if (!inputEl) {
            // console.log('xxxxxx createElement input');
            inputEl = document.createElement('input');
            inputEl.id = 'file_input';
            inputEl.setAttribute('id', 'file_input');
            inputEl.setAttribute('type', 'file');
            inputEl.setAttribute('class', 'fileToUpload');
            inputEl.style.opacity = '0';
            inputEl.style.position = 'absolute';
            inputEl.setAttribute('left', '-999px');
            document.body.appendChild(inputEl);
        }

        accept = accept || ".*";
        inputEl.setAttribute('accept', accept);

        // inputEl.addEventListener('change', (event) => {
        //     console.log('xxx onchange1', event, inputEl.value);
        // });
        inputEl.onchange = (event) => {
            // console.log('xxx onchange2', event, inputEl.files);
            let files = inputEl.files
            if (files && files.length > 0) {
                var file = files[0];
                if (callback) callback(file);
            }
        }
        inputEl.click();
    }

    /**
     * 读取本地文件数据
     *
     * @param {File} file
     * @param {READ_FILE_TYPE} readType
     * @param {((result: string | ArrayBuffer) => void)} callback
     * @memberof FileMgr
     */
    readLocalFile(file: File, readType: READ_FILE_TYPE, callback: (result: string | ArrayBuffer) => void) {
        var reader = new FileReader();
        reader.onload = function (event) {
            if (callback) {
                if (reader.readyState == FileReader.DONE) {
                    // console.log('xxx FileReader', event, reader.result);
                    callback(reader.result);
                } else {
                    callback(null);
                }
            }
        };
        switch (readType) {
            case READ_FILE_TYPE.DATA_URL:
                reader.readAsDataURL(file);
                break;
            case READ_FILE_TYPE.TEXT:
                reader.readAsText(file);   //作为字符串读出
                //reader.readAsText(file,'gb2312');   //默认是用utf-8格式输出的,想指定输出格式就再添加一个参数,像txt的ANSI格式只能用国标才能显示出来
                break;
            case READ_FILE_TYPE.BINARY:
                reader.readAsBinaryString(file);
                break;
            case READ_FILE_TYPE.ARRAYBUFFER:
                reader.readAsArrayBuffer(file);
                break;
        }
    }
   
    /**
     * 保存数据到本地
     *
     * @param {*} textToWrite       要保存的文件内容
     * @param {*} fileNameToSaveAs  要保存的文件名
     * @memberof FileMgr
     */
    saveForBrowser(textToWrite, fileNameToSaveAs) {    
        if (cc.sys.isBrowser) {        
            console.log("浏览器");        
            let textFileAsBlob = new Blob([textToWrite], {type:'application/json'});        
            let downloadLink = document.createElement("a");        
            downloadLink.download = fileNameToSaveAs;        
            downloadLink.innerHTML = "Download File";        
            if (window.webkitURL != null){            
                // Chrome allows the link to be clicked            
                // without actually adding it to the DOM.            
                downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);        
            }else{            
                // Firefox requires the link to be added to the DOM            
                // before it can be clicked.            
                downloadLink.href = window.URL.createObjectURL(textFileAsBlob);            
                // downloadLink.onclick = destroyClickedElement;            
                downloadLink.style.display = "none";            
                document.body.appendChild(downloadLink);        
            }        
                
            downloadLink.click();    
        } 
    }

}

cocos creator 实现文件读写功能 网页版本(一)_第1张图片

你可能感兴趣的:(creator,ts,js,typescript,cocos-creator)