Firebase非常新,我正在尝试做一个简单的任务 - 从我的PhoneGap HTML / JS应用程序上传文件到Firebase。图像位于页面上的Img元素中,当用户点击上传按钮时,我试图从元素中的文件中捕获所需的数据,但我没有太多运气。
我的尝试基于此Firecast:https://www.youtube.com/watch?v=SpxHVrpfGgU,区别在于我没有使用文件选择器。我发现的所有示例都使用文件选择器,因此我不确定如何处理页面上已有的文件。当它到达storageRef.put()时我得到这个错误:
{t: "storage/invalid-argument", e: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", n: null, r: "FirebaseError"}
所以我知道我没有通过Firebase需要的东西,但这就是我所拥有的。
这是我的HTML:
<img class='center' id="myImage" src="https://firebasestorage.googleapis.com/v0/b/********e.appspot.com/o/images%2F2014%20(39).JPG?alt=media&token=9c3d1613-c880-4437-abf9-f59bbcdc885bG">
<label class="center">Choose a category for the photo:
<select class="center" id="categories"></select>
</label>
<label class="">
<button class="button button-block button-balanced padding" id="uploadpicture">Upload Photo</button>
</label>
这是我的剧本:
<script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script>
<script>
$(document).ready(function(){
// Initialize Firebase
var config = {
apiKey: "AIzaSyCN***********POk",
authDomain: "***-storage.firebaseapp.com",
databaseURL: "https://****oto-storage.firebaseio.com",
projectId: "***w-photo-storage",
storageBucket: "*****hoto-storage.appspot.com",
messagingSenderId: "2*****4314287"
};
firebase.initializeApp(config);
function uploadImage(){
var img_file = document.getElementById("myImage");
var d = new Date();
var dateString = d.toISOString();
img_file.name = dateString;
var storageRef = firebase.storage().ref('photowPhotos/' + img_file.name);
var task = storageRef.put(img_file);
task.on('state_changed',
function error(err){
alert(err);
},
function complete(){
alert("Upload successful!")
}
);
}
$('#uploadpicture').on('click', uploadImage);
});
</script>
答案 0 :(得分:1)
我有类似的问题,这是代码。
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();
var getFileBlob = function(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function(blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function(blob) {
cb(blobToFile(blob, 'test.jpg'));
});
};
getFileObject(imageData, function(fileObject) {
var uploadTask = storageRef.child('images/test.jpg').put(fileObject);
uploadTask.on('state_changed', function(snapshot) {
console.log(snapshot);
}, function(error) {
console.log(error);
}, function() {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
// handle image here
});
});
}