Ad

How Do I Upload A File To Firebase Storage?

<head>
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-app.js"> 
</script>
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-auth.js"> 
</script>
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-database.js"> 
</script>
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-storage.js"> 
</script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<input type="file" value="upload" id="fileButton"/>
<progress value="0" max="100" id="uploader">0%</progress>
</body>
</html>

////Inside index.js////

var firebaseConfig = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***m",
messagingSenderId: "***",
appId: "***", 
};

// Initialize Firebase //
firebase.initializeApp(firebaseConfig);

// Upload File //
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');

fileButton.addEventListener('change', function(e) {
var file = evt.target.files[0];
var storageRef = firebase.storage().ref('files_new/' + file.name);
var task = storageRef.put(file);

task.on('state_changed', 

function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err) {
console.error();
},
function complete() {
console.log('success!');
}
);
});

What am I doing wrong? files are not uploading to the storage and progress bar is not working either.

All addresses and keys from config are correct as other functions from index.js are working, i.e Authentication

I did the whole thing from this link: https://www.youtube.com/watch?v=SpxHVrpfGgU

Ad

Answer

I think what's wrong is the reference. Get the storage ref first then create a child. Here is an example that works (at least for me):

const storageRef = firebase.storage().ref();
const fileRef = storageRef.child('files_new/' + file.name);
const task = fileRef.put(file);

task.on('state_changed',
  (snapshot) => { /* progress */ },
  (error) => { /* error */ },
  () => { /* complete */ }
)

with file beeing your file as above mentioned.

Ad
source: stackoverflow.com
Ad