Ang*_*ner 2 javascript cordova firebase firebase-storage
我正在尝试将我的Cordova应用程序中的图像上传到新的Firebase存储.这是我到目前为止所尝试的.
// Get the image from PhotoLibrary
navigator.camera.getPicture(onSuccess, onFail, {
quality: quality,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI,
targetWidth: imageSize,
targetHeight: imageSize
});
function onSuccess(imageData) {
var storageRef = firebase.storage().ref();
window.resolveLocalFileSystemURL(imageData,
function(fileEntry) {
fileEntry.file(function(file) {
var uploadTask = storageRef.child('images/test.jpg').put(file);
uploadTask.on('state_changed', function(snapshot){
console.log(snapshot);
});
}
)
};Run Code Online (Sandbox Code Playgroud)
这会导致以下错误
FirebaseError: Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.
Run Code Online (Sandbox Code Playgroud)
我尝试过的另一件事是将图像作为base64并转换为Blob,但结果相同.
有谁知道如何以Firebase存储所需的Javascript文件或Blob格式获取图像?谢谢!
小智 6
不喜欢将XMLHhttpRequest用于本地文件,因此在使用Cordova File Plugin之后我终于开始工作了.希望它可以帮到某人!
function MainController($scope, $cordovaCamera, $cordovaFile) {
$scope.capturarFoto = function (type) {
var opcionesCaptura = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType[type.toUpperCase()],
};
$cordovaCamera.getPicture(opcionesCaptura)
.then(procesarImagen, procesarError);
};
function procesarImagen(pathImagen) {
var directorioFuente = pathImagen.substring(0, pathImagen.lastIndexOf('/') + 1),
archivoFuente = pathImagen.substring(pathImagen.lastIndexOf('/') + 1, pathImagen.length),
nombreParaGuardar = new Date().valueOf() + archivoFuente;
$cordovaFile.readAsArrayBuffer(directorioFuente, archivoFuente)
.then(function (success) {
var blob = new Blob([success], {type: 'image/jpeg'});
enviarFirebase(blob, nombreParaGuardar);
}, function (error) {
console.error(error);
});
}
function enviarFirebase(file, nombre) {
var storageRef = firebase.storage().ref();
var uploadTask = storageRef.child('images/' + nombre).put(file);
uploadTask.on('state_changed', function (snapshot) {
console.info(snapshot);
}, function (error) {
console.error(error);
}, function () {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
});
}
function procesarError(error) {
console.error(JSON.stringify(error));
}
Run Code Online (Sandbox Code Playgroud)
}
正如@juanwmedia在他的回答中所说,我不喜欢将XMLHhttpRequest用于本地文件,所以这里是他没有使用ngCordova的答案,只是简单的cordova-plugin-file:
navigator.camera.getPicture(function (imageUri) {
window.resolveLocalFileSystemURL(imageUri, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
// This blob object can be saved to firebase
var blob = new Blob([new Uint8Array(this.result)], { type: "image/jpeg" });
sendToFirebase(blob);
};
reader.readAsArrayBuffer(file);
});
}, function (error) {
errorCallback(error);
});
}, errorCallback, options);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5921 次 |
| 最近记录: |