1. 程式人生 > >Cocos creator製作微信小遊戲儲存圖片,音訊檔案到本地(手機,瀏覽器)

Cocos creator製作微信小遊戲儲存圖片,音訊檔案到本地(手機,瀏覽器)

cocos creator打包生成的wx-downloader.js檔案儲存到本地會報 no such file or directory 沒有上級目錄錯誤,這就我們自己修改這個檔案,主要用到了微信小程式中的api FileSystemManger.access 和 FileSystemManager.saveFile方法

程式碼如下:

/****************************************************************************
 Copyright (c) 2017 Chukong Technologies Inc.

 http://www.cocos.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated engine source code (the "Software"), a limited,
  worldwide, royalty-free, non-assignable, revocable and  non-exclusive license
 to use Cocos Creator solely to develop games on your target platforms. You shall
  not use Cocos Creator software for developing other software or tools that's
  used for developing games. You are not granted to publish, distribute,
  sublicense, and/or sell copies of Cocos Creator.

 The software or tools in this License Agreement are licensed, not sold.
 Chukong Aipu reserves all rights not expressly granted to you.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var ID = 'WXDownloader';

var non_text_format = [
    'js','png','jpg','bmp','jpeg','gif','ico','tiff','webp','image','mp3','ogg','wav','m4a','font','eot','ttf','woff','svg','ttc'
];
var readPath = '';
var fs = wx.getFileSystemManager();
// var readPath = '';
var WXDownloader = window.WXDownloader = function () {
    this.id = ID;
    this.async = true;
    this.pipeline = null;
    this.REMOTE_SERVER_ROOT = '';
};
WXDownloader.ID = ID;

WXDownloader.prototype.handle = function (item, callback) {
    if (item.type === 'js') {
        callback(null, null);
        return;
    }
    if (item.type === 'uuid') {
        var result = cc.Pipeline.Downloader.PackDownloader.load(item, callback);
        // handled by PackDownloader
        if (result !== undefined) {
            // null result
            if (!!result) {
                return result;
            }
            else {
                return;
            }
        }
    }
    var filePath = item.url;
    // Read from package
    fs.access({
        path: filePath,
        success: function () {
            if (item.type && non_text_format.indexOf(item.type) !== -1) {
                nextPipe(item, callback);
            }
            else {
                readText(item, callback);
            }
        },
        fail: function (res) {
            readFromLocal(item, callback);
        }
    });
};

WXDownloader.prototype.cleanOldAssets = function () {
    fs.getSavedFileList({
        success: function (res) {
            var list = res.fileList;
            if (list) {
                for (var i = 0; i < list.length; i++) {
                    var path = list[i].filePath;
                    fs.unlink({
                        filePath: list[i].filePath, 
                        success: function () {
                            cc.log('Removed local file ' + path + ' successfully!');
                        },
                        fail: function (res) {
                            cc.warn('Failed to remove file(' + path + '): ' + res ? res.errMsg : 'unknown error');
                        }
                    });
                }
            }
        },
        fail: function (res) {
            cc.warn('Failed to list all saved files: ' + res ? res.errMsg : 'unknown error');
        }
    });
};

WXDownloader.prototype.cleanAllAssets = function () {
    fs.getSavedFileList({
        success: function (res) {
            var list = res.fileList;
            if (list) {
                for (var i = 0; i < list.length; i++) {
                    var path = list[i].filePath;
                    fs.unlink({
                        filePath: list[i].filePath, 
                        success: function () {
                            cc.log('Removed local file ' + path + ' successfully!');
                        },
                        fail: function (res) {
                            cc.warn('Failed to remove file(' + path + '): ' + res ? res.errMsg : 'unknown error');
                        }
                    });
                }
            }
        },
        fail: function (res) {
            cc.warn('Failed to list all saved files: ' + res ? res.errMsg : 'unknown error');
        }
    });
};

var wxDownloader = window.wxDownloader = new WXDownloader();

function nextPipe (item, callback) {
    var queue = cc.LoadingItems.getQueue(item);
    queue.addListener(item.id, function (item) {
        if (item.error) {
            fs.unlink({
                filePath: item.url, 
                success: function () {
                    cc.log('Load failed, removed local file ' + item.url + ' successfully!');
                }
            });
        }
    });
    callback(null, null);
}

function readText (item, callback) {
    var url = item.url;
    fs.readFile({
        filePath: url,
        encoding: 'utf8',
        success: function (res) {
            item.states[cc.loader.downloader.id] = cc.Pipeline.ItemState.COMPLETE;
            callback(null, res.data);
        },
        fail: function (res) {
            cc.warn('Read file failed: ' + url);
            fs.unlink({
                filePath: url, 
                success: function () {
                    cc.log('Read file failed, removed local file ' + url + ' successfully!');
                }
            });
            callback({
                status: 0, 
                errorMessage: res && res.errMsg ? res.errMsg : "Read text file failed: " + url
            });
        }
    });
}

function readFromLocal (item, callback) {
    var localPath = wx.env.USER_DATA_PATH + '/' + item.url;
    // Read from local file cache
    console.log("開始讀取本地檔案<<---");
    console.log("localPath is ",localPath);
    //檢視目錄是否存在
    fs.access({
      path: localPath,
      success: function () {
        item.url = localPath;
        if (item.type && non_text_format.indexOf(item.type) !== -1) {
          nextPipe(item, callback);
        }
        else {
          readText(item, callback);
        }
      },
      fail: function (res) {
        // No remote server indicated, then continue to downloader
        if (!wxDownloader.REMOTE_SERVER_ROOT) {
          callback(null, null);
          return;
        }
        console.log("檔案或者資料夾不存在");
        downloadRemoteFile(item, callback);
      }
    });
}

function downloadRemoteFile (item, callback) {
    // Download from remote server
    var relatUrl = item.url;
    var remoteUrl = wxDownloader.REMOTE_SERVER_ROOT + '/' + relatUrl;
    item.url = remoteUrl;
    console.log("開始下載檔案-->>>",item.url);
    var downloadObj = {
      url: remoteUrl,
      header: null,
      success: function (res) {
        if (res.tempFilePath) {
          // Save to local path
          console.log("下載檔案成功");
          console.log("relatUrl is ",relatUrl);
          console.log(relatUrl.slice(0, relatUrl.lastIndexOf('/')));
          //獲得檔案的上級目錄
          var parentDir = relatUrl.slice(0, relatUrl.lastIndexOf('/'));
          var dirArr = [];
          //分割上級目錄成陣列
          dirArr = parentDir.split('/');
          console.log(dirArr);
          new Promise(function(resolve,reject){
            var startDir = '';
            dirArr.forEach(function (element) {
              startDir += element+'/';
              //建立資料夾
              fs.mkdir({
                dirPath: wx.env.USER_DATA_PATH + '/' + startDir,
                success: function () {
                  // console.log("建立資料夾成功");
                },
                fail: function (e) {
                  // console.log("建立資料夾失敗",e.errMsg);
                }
              })
            });
            resolve("建立檔案的所有父目錄成功");
          }).then(function(){
            var localPath = wx.env.USER_DATA_PATH + '/' + relatUrl;
            //建立relatUrl上級目錄
            console.log("儲存檔案路徑是:", localPath);
            fs.saveFile({
              tempFilePath: res.tempFilePath,
              filePath: localPath,
              success: function (res) {
                cc.log('Write file to ' + res.savedFilePath + ' successfully!');
                item.url = res.savedFilePath;
                if (item.type && non_text_format.indexOf(item.type) !== -1) {
                  nextPipe(item, callback);
                }
                else {
                  readText(item, callback);
                }
              },
              fail: function (e) {
                // Failed to save file, then just use remote url
                console.log("儲存檔案失敗!!", e.errMsg);
                //如果上級目錄不存在
                callback(null, null);
              }
            });
          });
          
          
          
        } else if (res.statusCode === 404) {
          cc.warn("Download file failed: " + remoteUrl);
          callback({
            status: 0,
            errorMessage: res && res.errMsg ? res.errMsg : "Download file failed: " + remoteUrl
          });
        }
      },
      fail: function (res) {
        // Continue to try download with downloader, most probably will also fail
        callback(null, null);
      }
    }
    if(item.url.indexOf('.png') > -1){
      var o = {
        "content-type":"image/png"
      }
      downloadObj.header = o;
    }else if(item.url.indexOf('.mp3') > -1){
      var o1 = {
        "content-type":"audio/mp3"
      }
      downloadObj.header = o1;
    }
    wx.downloadFile(downloadObj);
}

// function downloadRemoteTextFile (item, callback) {
//     // Download from remote server
//     var relatUrl = item.url;
//     var remoteUrl = wxDownloader.REMOTE_SERVER_ROOT + '/' + relatUrl;
//     item.url = remoteUrl;
//     wx.request({
//         url: remoteUrl,
//         success: function(res) {
//             if (res.data) {
//                 if (res.statusCode === 200 || res.statusCode === 0) {
//                     var data = res.data;
//                     item.states[cc.loader.downloader.ID] = cc.Pipeline.ItemState.COMPLETE;
//                     if (data) {
//                         if (typeof data !== 'string' && !(data instanceof ArrayBuffer)) {
//                             // Should we check if item.type is json ? If not, loader behavior could be different
//                             item.states[cc.loader.loader.ID] = cc.Pipeline.ItemState.COMPLETE;
//                             callback(null, data);
//                             data = JSON.stringify(data);
//                         }
//                         else {
//                             callback(null, data);
//                         }
//                     }

//                     // Save to local path
//                     var localPath = wx.env.USER_DATA_PATH + '/' + relatUrl;
//                     // Should recursively mkdir first
//                     fs.writeFile({
//                         filePath: localPath,
//                         data: data,
//                         encoding: 'utf8',
//                         success: function (res) {
//                             cc.log('Write file to ' + res.savedFilePath + ' successfully!');
//                         },
//                         fail: function (res) {
//                             // undone implementation
//                         }
//                     });
//                 } else {
//                     cc.warn("Download text file failed: " + remoteUrl);
//                     callback({
//                         status:0, 
//                         errorMessage: res && res.errMsg ? res.errMsg : "Download text file failed: " + remoteUrl
//                     });
//                 }
//             }
//         },
//         fail: function (res) {
//             // Continue to try download with downloader, most probably will also fail
//             callback(null, null);
//         }
//     });
// }

這樣就可以愉快的將圖片和音訊檔案存放到本地了。如果哪裡有待改進的地方望給為老師及時指正謝謝。