使用图片URI将照片上传到Firebase存储

时间:2018-07-20 22:01:33

标签: javascript cordova firebase phonegap-plugins firebase-storage

我目前正在尝试将照片上传到Apache Cordova应用程序中Firebase应用程序的存储中。我目前使用以下代码获取照片的URI:

function getPhotoFromAlbum() {

    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality: 50,
        sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
        destinationType: navigator.camera.DestinationType.FILE_URI
    });
}

function onPhotoURISuccess(imageURI) {
    var image = document.getElementById('image');
    image.style.display = 'block';
    image.src = imageURI;

    getFileEntry(imageURI);

}

然后尝试使用以下功能将图像转换为文件并将其推送到我的Firebase存储中:

function getFileEntry(imgUri) {
    window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {

        console.log("got file: " + fileEntry.fullPath);
        var filename = "test.jpg";
        var storageRef = firebase.storage().ref('/images/' + filename);
        var uploadTask = storageRef.put(fileEntry);

    }, function () {
        // If don't get the FileEntry (which may happen when testing
        // on some emulators), copy to a new FileEntry.
        createNewFileEntry(imgUri);
    });
}

我同时安装了文件和相机cordova插件,尝试执行此操作时遇到的唯一错误是

Error in Success callbackId: File1733312835 : [object Object]

这只是来自cordova.js的错误消息

我还知道我的Firebase存储设置正确,因为我已经通过仿真器对其进行了测试,方法是添加文件输入并将用户添加的任何文件成功上传到Firebase存储。

是否可以使用这种通过图像URI将图像转换为文件然后再上传的方法将文件上传到Firebase存储?如果是这样,那么正确的方法是什么?我的操作方式有什么问题?

2 个答案:

答案 0 :(得分:1)

我能够通过使用数据URL完成上传图片。下面是我的代码:

var filename = "test.jpg";
                    var storageRef = firebase.storage().ref('/images/' + filename);

                    var message = 'data:image/jpg;base64,' + imageUri;
                    storageRef.putString(message, 'data_url').then(function (snapshot) {
                        console.log('Uploaded a data_url string!');
                    });

答案 1 :(得分:0)

  

是否可以使用这种通过图像URI将图像转换为文件然后再上传的方法将文件上传到Firebase存储?如果是这样,那么正确的方法是什么?我的操作方式有什么问题?

是的,可以通过文件的URI在firebase上上传文件。但是,您必须遵循正确的方法。

1。。您必须在文件firebase操作完成后将数据存储在reading中。您可以为此使用FileReader.onloadend

2。。通过使用data_url,您可以存储到firebase

以下是片段,以使内容更加清晰:

function getFileEntry(imgUri) {
    window.resolveLocalFileSystemURL(imgUri, function onSuccess(fileEntry) {
            fileEntry.file(function(file) { 
                var reader = new FileReader();
                reader.onloadend = function() {
                    filename = "test.jpg";
                var storageRef = firebase.storage().ref('/images/' + filename);
             var data = 'data:image/jpg;base64,' + imgUri;
                storageRef.putString(data, 'data_url').then(function (snapshot) {
                    console.log('Image is uploaded by base64 format...');
                });
                };
                reader.readAsArrayBuffer(file);
            });
        },
        function onError(err) {
             console.log(err);
             createNewFileEntry(imgUri);
        });
}
相关问题