Javascript,上传到Firebase,转换为Blob和403地址无法访问

时间:2018-08-17 11:36:49

标签: javascript firebase firebase-storage

第一次尝试掌握Firebase。我一直在遵循Google的代码示例,下面的代码是“完整示例”中95%的复制粘贴,我只是替换了文件路径并转换为Blob

我有两个问题:

首先,我不得不将文件转换为blob,但是google firebase示例未提及它;知道为什么吗?

然后我遇到错误ERR_ADDRESS_UNREACHABLE

OPTIONS https://firebasestorage.googleapis.com/v0/b/test-project-c2e31.appspot.com/o?name=images%2Fundefined net::ERR_ADDRESS_UNREACHABLE

这是我的代码

var file = 'files/van.jpg'

// Create a root reference
var storageRef = firebase.storage().ref();

// Create a reference to 'van.jpg'
var mountainsRef = storageRef.child('van.jpg');

// Create a reference to 'images/van.jpg'
var mountainImagesRef = storageRef.child('images/van.jpg');

// Create the file metadata
var metadata = {
  contentType: 'image/jpeg'
};

// convert to blob
var blob = new Blob([file], { type: "image/jpeg" });

// Upload file and metadata to the object 'images/van.jpg'
var uploadTask = storageRef.child('images/' + blob.name).put(blob, metadata);

// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
  case firebase.storage.TaskState.PAUSED: // or 'paused'
    console.log('Upload is paused');
    break;
  case firebase.storage.TaskState.RUNNING: // or 'running'
    console.log('Upload is running');
    break;
}
}, function(error) {

// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
  // User doesn't have permission to access the object
  break;

case 'storage/canceled':
  // User canceled the upload
  break;

case 'storage/unknown':
  // Unknown error occurred, inspect error.serverResponse
  break;
}
}, function() {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});

0 个答案:

没有答案