你能用 ngCordova 将 base64 数据保存为文件吗?

Can you save base64 data as a file with ngCordova?

在这个tutorial中,作者使用FileURI将图片从临时位置复制到设备位置,最后returning nativeURL这个复制的文件。

window.resolveLocalFileSystemURL(fileURI, success, fail);

而不是 FileURI 我有一个 base64 string (imageData) 我也想保存在设备上位置和 return 此已保存图像的 nativeURL

这可能吗?如何使用 ngCordova 实现这一目标?

1.在控制器

中使用canvas
$scope.drawAndSave = function() {

    $scope.targetImages = [{nativeURL: "img/newyork.jpg"}, {nativeURL: "img/newyork.jpg"}]

    drawCanvas().then(function(data){
      $scope.outputImages = data; // works fine, can save it

      for (var i = 0; i < data.length; i++) { 
        FileFactory.saveCanvasToDataUrl(data[i])
      }

    });

    function drawCanvas() {
      var pResults = $scope.targetImages.map(function (imageObj) {
        return drawToCanvas(imageObj.nativeURL);
      });
      return $q.all(pResults);
    }

    function drawToCanvas(nativeURL) {
      return $q(function (resolve) {
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var img = new Image();
        img.src = nativeURL;

        img.onload = function () {
            ctx.drawImage(img, 0, 0);
            resolve(canvas.toDataURL("image/jpeg"));
        };

      });
    } // draw to canvas

  }

2。将 canvas 保存为输入图像 fileURI canvas.toDataUrl() dataURI.

.factory('FileFactory', function($cordovaFile, $q) {

    var saveCanvasToDataUrl = function(imageData) {
        copyFileURI(imageData) 
    }

    // // http://devdactic.com/how-to-capture-and-store-images-with-ionic/
    // todo: get file uri and copy it
    var copyFileURI = function(fileURI) {

        window.alert("saving ")

        var q = $q.defer();
        onImageSuccess(fileURI);
        function onImageSuccess(fileURI) {
            createFileEntry(fileURI);
        }
        function createFileEntry(fileURI) {
            window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
        }
        function copyFile(fileEntry) {
            var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
            var newName = makeid() + name;
            window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
                fileEntry.copyTo(
                    fileSystem2,
                    newName,
                    onCopySuccess,
                    fail
            );
            },
            fail);
        }
        function onCopySuccess(entry) {
            q.resolve(entry.nativeURL) 
        }
        function fail(error) {
            q.reject(error)
            window.alert("fail: " + JSON.stringify(error))
        }
        function makeid() {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (var i=0; i < 5; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
            }
            return text;
        }

        return q.promise;
    } // copy file uri, return new native url


    var removeFile = function(nativeURL) {

        var name = nativeURL.substr(nativeURL.lastIndexOf('/') + 1);
        window.alert("trying to delete nativeURL name: " + nativeURL)
        window.alert("cordova file directory: " + cordova.file.dataDirectory)
        window.alert('name: ' + name)

        $cordovaFile.checkFile(cordova.file.dataDirectory, name)
        .then(function (success) {

            window.alert("file found " + success)

            $cordovaFile.removeFile(cordova.file.dataDirectory, name)
                .then(function (success) {
                    // success
                    window.alert("file deleted " + success)
                }, function (error) {
                // error
                window.alert("file not deleted error " + error)
                });

        }, function (error) {
        // error
            window.alert("file not ound " + JSON.stringify(error))
        });

    }

    return {
        copyFileURI: copyFileURI, 
        removeFile: removeFile,
        saveCanvasToDataUrl: saveCanvasToDataUrl
    }

});

尝试使用以下代码将 base64 字符串保存到文件

// I assume your base64 string is stored in a variable 'imageData'
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
    fileSystem.root.getFile("image.jpg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
    console.log("Start creating image file");
    writer.seek(0);
    writer.write(imageData);
    console.log("End creating image file. File created");
}

将以上所有组合成一个函数

function savefile(dataurl){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
    function (fileSystem) {
        fileSystem.root.getFile("image.jpg", {create: true, exclusive: false}, 
            function (fileEntry) {
                fileEntry.createWriter(function (writer) {
                    console.log("Start creating image file");
                    writer.seek(0);
                    writer.write(dataurl);
                    console.log("End creating image file. File created");
                }, fail);
            }, fail);
    }, fail);
}

function fail(){
    console.log("Error");
}

现在您可以通过 savefile(dataurl) 调用函数,其中 dataurl 是 base64 字符串

更新:

以上版本没有文件夹选择。在下面的函数中 app_folder_name 变量必须替换为设备中的文件夹。

function savefile(dataurl){
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
    function (fileSystem) {
        fileSystem.root.getDirectory( app_folder_name, {create:true, exclusive: false},
        function(directory) {
            directory.root.getFile("image.jpg", {create: true, exclusive: false}, 
            function (fileEntry) {
                fileEntry.createWriter(function (writer) {
                    console.log("Start creating image file");
                    writer.seek(0);
                    writer.write(dataurl);
                    console.log("End creating image file. File created");
                }, fail);
            }, fail);
        }, fail);
    }, fail);
}