Firebase storage cant upload files with button - javascript

var file;
/////detect if file is upload/////////
$("#file").on('change',function(e){
file = e.target.files[0];
});
/////function for upload to storage button when clicked///////////
function uploadFile(){
var storageRef = firebase.storage().ref('/pics/'+file.name);
var task = storageRef.put(file);
console.log("yes");
}

On my side, below code is working well, and that is almost the same as the question code.
<html>
<header>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var config = {
apiKey: " ",
authDomain: " ",
databaseURL: " ",
projectId: " ",
storageBucket: " ",
messagingSenderId: " "
};
firebase.initializeApp(config);
$(document).ready(function () {
var file;
$("#file").on('change', function (e) {
file = e.target.files[0];
});
$('#btnUpload')
.click(function () {
if (file == null || file.name == null) {
alert("Please select file");
return;
}
var storageRef = firebase.storage().ref('/pics/' + file.name);
var task = storageRef.put(file)
.then((snapshot) => {
console.log('Uploaded a blob or file!', snapshot);
})
.catch(error => {
console.error(error)
});
});
});
</script>
</header>
<body>
<h3>Upload File</h3>
<div>
<input type="file" id="file" class="form">
<button class="btn btn-danger" id="btnUpload">Upload</button>
</div>
</body>
</html>
Updated:
Only added then, catch for debug.
But, working well.
var task = storageRef.put(file)
.then((snapshot) => {
console.log('Uploaded a blob or file!', snapshot);
})
.catch(error => {
console.error(error)
});

Related

firebase storage ref is not a function

Im new in web development . i tried to find an answer all over the internet in the past 24 hours without success and now im reaching out here
this is my err :
Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_3_.storage.ref is not a function
this is the firebase.js file :
import { initializeApp } from 'firebase/app';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);
and im importing the storage in the component like that :
import {storage} from "../../firebase";
this is the upload func :
const upload = (items) => {
items.forEach((item) => {
const fileName = new Date().getTime() + item.label + item.file.name;
const uploadTask = storage.ref(`/items/${fileName}`).put(item.file);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
},
(error) => {
console.log(error);
},
() => {
uploadTask.snapshot.ref.getDownloadURL().then((url) => {
setMovie((prev) => {
return { ...prev, [item.label]: url };
});
setUploaded((prev) => prev + 1);
});
}
);
});
};
any suggestions ?
You are using the syntax for the legacy namespaced Firebase JS SDK (v8 and older) with the newer modular Firebase SDK (v9 and newer).
Instead of storage.ref(), you need to be using ref(storage, path):
import { storage } from "../../firebase"
import { ref, uploadBytes } from "firebase/storage";
const upload = (items) => {
items.forEach((item, index) => {
const storageRef = ref(storage, `/items/${fileName}`);
const uploadTask = uploadBytes(storageRef, item.file);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 1000)/10;
console.log(`Upload #${index+1} is ${progress}% done`);
},
(error) => {
console.log(error);
},
() => {
console.log(`Upload #${index+1} is complete, fetching URL...`);
getDownloadURL(storageRef)
.then((url) => {
console.log(`Upload #${index+1} is now available at ${url}.`);
setMovie((prev) => {
return { ...prev, [item.label]: url };
});
setUploaded((prev) => prev + 1);
})
.catch((error) => {
console.log(error);
});
}
);
});
}
I encourage you to read the documentation completely and read the migration guide so that you can see which SDK version the code you are working off of was built for.
Note: You should further improve this code to handle errors better, such as set an error message visible to the user for failed uploads.

Onclick is not defined - EventListener null

The problem is that the onlclick returns "main.html:1 Uncaught ReferenceError: removePost is not defined at HTMLButtonElement.onclick (main.html:1)" I need to load the function removePost to erase the post with the specific id. After that I tried the same trick but with the eventListener (see in the final of the code) but returns null, the html reference it seems to be out of scope. Uncaught TypeError: Cannot read property 'addEventListener' of null at main.js:70.
Any ideas? thx in advance.
HTML
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<title>Count Likes</title>
</head>
<body>
<div class="root"></div>
<div class="CountLike" id="Like Count">
<button class="button button1">
<i class="fa fa-heart"></i> Like <span class="counterStat">...</span>
</button>
</div>
<div class="formContainer">
<input id="nameInput" type="text" placeholder="Escribe tu nombre" />
<input id="bodyInput" type="text" placeholder="Ingresa comentario" />
<button id="btnSend">Publicar</button>
</div>
<table class="table">
<tbody id="table"></tbody>
</table>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyBoHBd8UGJ2oFxyEu9lqbIWmg_j-MvcYZQ",
authDomain: "like-button-2203f.firebaseapp.com",
databaseURL: "https://like-button-2203f-default-rtdb.firebaseio.com",
projectId: "like-button-2203f",
storageBucket: "like-button-2203f.appspot.com",
messagingSenderId: "949206080621",
appId: "1:949206080621:web:8b2146c19e8c082b913364",
measurementId: "G-REJZ56MGNY",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
</script>
<script type="module" src="main.js"></script>
</body>
</html>
JAVASCRIPT
const db = firebase.firestore();
const dCounters = document.querySelectorAll(".CountLike");
[].forEach.call(dCounters, function (dCounter) {
const el = dCounter.querySelector("button");
const cId = dCounter.id;
const dDatabase = firebase.database().ref("Like Number Counter").child(cId);
// get firebase data
dDatabase.on("value", function (snap) {
const data = snap.val() || 0;
dCounter.querySelector("span").innerHTML = data;
});
// set firebase data
el.addEventListener("click", function () {
dDatabase.transaction(function (dCount) {
return (dCount || 0) + 1;
});
});
});
document.getElementById("btnSend").addEventListener("click", () => {
let name = document.getElementById("nameInput").value;
let body = document.getElementById("bodyInput").value;
db.collection("post")
.add({
name: name,
body: body,
})
.then(function (docRef) {
console.log("id ", docRef.id);
document.getElementById("nameInput").value = "";
document.getElementById("bodyInput").value = "";
})
.catch(function (error) {
console.error("Error ", error);
});
});
const table = document.getElementById("table");
db.collection("post").onSnapshot((querySnapshot) => {
table.innerHTML = "";
querySnapshot.forEach((doc) => {
// console.log(`${doc.id}=>${doc.data().name}`);
table.innerHTML += `
<tr>
<th scope='row'>${doc.id}</th>
<td>${doc.data().name}</td>
<td>${doc.data().body}</td>
<td><button onclick="removePost('${doc.id}')"
id="btnRemove" class="far fa-trash-alt"></button></td>
<td><button id="editPost" class="far fa-edit"></button></td>
</tr>`;
});
});
function removePost(id) {
db.collection("post")
.doc(id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
}
EventListener
document.getElementById("btnRemove").addEventListener("click", (evt) => {
db.collection("post")
.doc(evt.target.doc.id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
});

How to call javascript function defined in another file from HTML?

I am trying to write a website, but when I try to call a JavaScript function defined in another file from my HTML code I get the following error
Uncaught ReferenceError: fetchConfs is not defined at admin.html:46
I did import the script in the <head> portion of the HTML, but for some reason, I am still getting the error.
admin.html:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="bundle.css">
<script type="text/javascript" src="bundle.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-firestore.js"></script>
<title>Dilo+</title>
</head>
<header class="header">
<img src="logo.png">
<p>Sobreviviendo a lo imposible</p>
</header>
<body>
<script type="text/javascript">
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
var email = user.email;
user.getIdToken().then(function (accessToken) {
document.getElementById("greeter").textContent = "Hola " + email;
});
} else {
window.location.href = '/login.html'
}
}, function (error) {
console.log(error);
});
};
window.addEventListener('load', function () {
initApp()
document.getElementById("logout").onclick = function logout() {
firebase.auth().signOut().then(function () { window.location.href = '/login.html' });
}
var confs = fetchConfs();
});
</script>
<h1 id="greeter">Error, inicia sesión para continuar</h1>
<button class="mdc-button foo-button" id="logout" style="float: right;">
Cerrar Sesión
</button>
</body>
</html>
app.js (This file is compiled to bundle.js using webpacks before deploying):
import {MDCRipple} from '#material/ripple/index';
import { MDCTextField } from '#material/textfield';
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/firebase-auth';
const ripple = new MDCRipple(document.querySelector('.foo-button'));
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
document.getElementById("tbut").onclick = function submitForm() {
var date = Date.now().toString()
var x = document.getElementById("conf").value;
firebase.firestore().collection("confesiones").doc(date).set({
conf: x
})
.then(function () {
console.log("Document successfully written!");
var y = document.getElementById("conf").value;
console.log("input " + x)
alert("Exito");
})
.catch(function (error) {
console.error("Error writing document: ", error);
alert("Error envíando tu confesión")
});
document.getElementById("conf").reset();
}
function fetchConfs() {
var confs = db.collection("confesiones").where(firebase.firestore.FieldPath.documentId(), "!=", "root").get();
return confs;
}
I already tried assigning fetchConfs() to the window object or to a global variable, but I'm still getting the same error.
Note: I am using webpacks and other npm plugins to compile js and sass code to static files for deployment.
Scripts are run in the order that they are listed in <head>, then any in the body. If the function is in a script listed later, that function may not be defined yet when it is run.
To fix this, define fetchConfs earlier on.

how to get the path of an uploaded file in reactjs

how to get the path of an uploaded file in reactjs.
I use the file upload to upload a file
render() {
return (
<div>
<input type="file" onChange={this.fileChangedHandler} />
<button onClick={this.uploadHandler}>Upload!</button>
</div>
)
}
then bind the uploadHandler
this.uploadHandler = this.uploadHandler.bind(this)
and
uploadHandler = () => {
console.log("the selected file is : "+this.state.selectedFile.name)
}
Here I'm getting its name. I want to get the file path.
If you want to upload an image without posting to a server, you can use base64.
reactjs:
this.state = {
imgUpload: '',
}
...
this.getBase64 = this.getBase64.bind(this)
...
getBase64(e) {
var file = e.target.files[0]
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
this.setState({
imgUpload: reader.result
})
};
reader.onerror = function (error) {
console.log('Error: ', error);
}
}
...
<div>
<input type="file" className="input-file" name="imgUpload" accept='.png' onChange={this.getBase64} />
</div>
Then you can use {this.state.imgUpload} to access the base64 string and can manipulate the image.

Firebase Storage and PhoneGap - Sending a file that's in an Img element

Very new to Firebase and I'm trying to do what seems like a simple task - upload a file to Firebase from my PhoneGap HTML/JS app. The image is in an Img element on the page, and when a user taps the upload button I'm trying to capture the data I need from the file that's in the element but I'm not having much luck.
I'm basing my attempt off this Firecast: https://www.youtube.com/watch?v=SpxHVrpfGgU with the difference being I'm not using a file picker. All the examples I've found use file pickers so I'm not sure how to deal with a file that's already on the page. I get this error when it gets to storageRef.put():
{t: "storage/invalid-argument", e: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", n: null, r: "FirebaseError"}
So I know I'm not passing what Firebase needs, but that's as far as I've got.
This is my 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>
And this is my script:
<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>
I had a similar issue, here is the code.
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
});
});
}

Categories

Resources