Firebase存储将图像成功上传到Firebase存储后获得下载URL
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Firebase存储将图像成功上传到Firebase存储后获得下载URL相关的知识,希望对你有一定的参考价值。
这是上传图像并获取下载网址的完整代码图片已成功上传,但未打印下载网址
<html>
<head>
<title> firebase save</title>
<style media="screen">
body{
display : flex;
min-height: 100vh;
width : 100%;
padding : 0;
margin:0;
align-items: center;
justify-content: center;
flex-direction: column;
}
#uploader{
-webkit-appearance: none;
appearance: none;
width: 50%;
margin-bottom: 10px;
}
</style>
</head>
<body>
<progress value="0" max = "100" id="uploader" > 0%</progress>
<input type = "file" value="upload" id="fileButton" />
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
//firebase initialization
};
firebase.initializeApp(config);
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change' , function(e) {
var file= e.target.files[0];
var storageRef = firebase.storage().ref('pics/' + file.name);
var task = storageRef.put(file); // <--- See the difference here
task.on('state_changed' ,
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err){
},
function complete(){
}
);
});
</script>
<script>
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("pics/1.jpg", downloadURL);
document .writeln(downloadURL);
});
</script>
</body>
</html>
我也尝试过这种方法
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("pics/1.jpg", downloadURL);
});
答案
来自文档:
put
put(data: Blob | Uint8Array | ArrayBuffer, metadata?: UploadMetadata): UploadTask Uploads data to this reference's location
。可选元数据:UploadMetadata新上传的对象的元数据。
返回UploadTask可用于监视和管理上载的对象。
put
方法返回类型为UploadTask
的值。 UploadTask
包含属性snapshot
,因此:
var task = storageRef.put(file);
function progress(){
var percentage = (task.snapshot.bytesTransferred / task.snapshot.totalBytes) * 100;
uploader.value = percentage;
以上是关于Firebase存储将图像成功上传到Firebase存储后获得下载URL的主要内容,如果未能解决你的问题,请参考以下文章
Firebase存储将图像成功上传到Firebase存储后获得下载URL
将图像存储在 Firebase Storage 中并将元数据保存在 Firebase Cloud Firestore(测试版)中