天天看點

CocosCreator開發筆記(11)-如何實作寫檔案

在CocosCreator官方文檔中沒有提供跨平台的通用寫檔案接口。如果運作環境是浏覽器,有一個替代方案可以實作把内容儲存到檔案,效果相當于下載下傳了一個檔案到本地。代碼如下:

// 儲存字元串内容到檔案。
// 效果相當于從浏覽器下載下傳了一個檔案到本地。
// textToWrite - 要儲存的檔案内容
// fileNameToSaveAs - 要儲存的檔案名
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();
    }
}