如何将照片从图库复制到dataDirectory?

时间:2015-06-11 15:50:51

标签: javascript cordova plugins ionic-framework

我正在尝试将照片库中的文件复制到Android 5.0设备上的dataDirectory。 不幸的是,Cordova相机插件以如下格式返回路径:content:// media / external / images / media / 8793

 var options = {
                quality: 50,
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                saveToPhotoAlbum: false
            };

            return $cordovaCamera.getPicture(options).then(function (result) {
                return handlePictureResult(result);
            })

$ cordovaFile.copyFile('content:// media / external / images / media / 8793',null,cordova.file.dataDirectory,newFileName)根本不起作用。

任何想法如何将文件从图库(带有content://的路径)复制到cordova.file.dataDirectory?

2 个答案:

答案 0 :(得分:5)

以下是您应该如何处理它(使用fileTransfer plugin代替file one):

app.controller(
    'MainController',
    [
        '$scope', '$cordovaCamera', '$cordovaFileTransfer',
        function($scope, $cordovaCamera, $cordovaFileTransfer)
        {
            $scope.images = { imageUri: '' };

            $scope.getImage = function()
            {
                var options = {
                    quality: 50,
                    destinationType: Camera.DestinationType.FILE_URI,
                    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(
                    function(fileUri)
                    {
                        console.log(fileUri);

                        $cordovaFileTransfer.download(fileUri, cordova.file.dataDirectory + 'my-image.jpg', {}, true).then(
                            function(fileEntry)
                            {
                                $scope.images.imageUri = fileEntry.nativeURL;
                            },
                            function (error)
                            {
                                console.log(error);
                            }
                        );
                    },
                    function(error)
                    {
                        console.log(error);
                    }
                );
            }
        }
    ]
);

HTML(以防万一):

<section ng-controller="MainController">
    <img ng-src="{{ images.imageUri }}">
    <button ng-click="getImage()">GET IMAGE</button>
</section>

答案 1 :(得分:0)

您可以在base64上接收图像数据并自行保存。

我做了一个库,可以在cordova / HTML5上轻松管理FileAPI,也许对你有用:https://github.com/exos/cofs

var fs = new CoFS();

var options = {
    quality: 50,
    destinationType : navigator.camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY
};

return $cordovaCamera.getPicture(options).then(function (data) {
    fs.writeFile(
        cordova.file.dataDirectory + '/example.jpg',
        data,
        'base64',
        function (err) {
            // if not err, success!
        }
    );
});