Skip to content

Instantly share code, notes, and snippets.

@porfidev
Created December 6, 2022 03:54
Show Gist options
  • Save porfidev/089f237d671994ee8b944c0503871edc to your computer and use it in GitHub Desktop.
Save porfidev/089f237d671994ee8b944c0503871edc to your computer and use it in GitHub Desktop.
How to Upload image to Firebase Storage from URL
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload URL FILES</title>
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getStorage, ref, uploadBytes } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-storage.js';
function generateUUID() { // Public Domain/MIT
let d = new Date().getTime();//Timestamp
let d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16;//random number between 0 and 16
if (d > 0) {//Use timestamp until depleted
r = (d + r) % 16 | 0;
d = Math.floor(d / 16);
} else {//Use microseconds since page-load if supported
r = (d2 + r) % 16 | 0;
d2 = Math.floor(d2 / 16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
// Your web app's Firebase configuration
const firebaseConfig = await fetch('./firebaseConfig.json')
.then((response) => response.json());
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Storage and get a reference to the service
const storage = getStorage(app);
fetch('https://placekitten.com/300/300').then(function (response) {
return response.blob();
}).then(function (myBlob) {
const name = myBlob.type === 'image/jpeg' ? generateUUID() + '.jpg' : 'No Definido.jpg';
const newRef = ref(storage, 'imagenes/' + name);
uploadBytes(newRef, myBlob).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment