cnbu12oZsPUsXwMqS8ozdUYI5DesA4e6nbQsVzgG
Code Blogger Firebase (Database)
Sharing Code Blogger dengan Firebase (database)
Cara mudah menghubungkan Blog dengan Database, disini anda akan mempelajari memaksimalkan kekuatan Firebase dan Blogger

Menambahkan Gambar di blogger menggunakan Storage Firebase dan Firestore

hi, kali ini admin akan membagikan source code bagaimana membuat halaman page tanpa login untuk menyimpan Foto/Gambar/Image di blogger, Ya Bisa?
admin menggunakan 2 buah database yaitu Firestore database dan Storage database
Dimana gambar/image/photo akan disimpan di storage database dan data deskripsi dari Foto akan disimpan di Firestore.
code ini bisa anda tempatkan di halaman page ataupun post atau di widget javascript dihalaman layout. mohon diperhatikan cara tata letak penempatan kode kode dibawah ini
buat halaman baru/page di blogger dan copy paste kode berikut:
Beri judul page tersebut dan simpan

<title>Upload Image and Description</title>

    <form id="uploadForm">
        <input type="file" id="imageFile" accept="image/*">
        <br>
        <br>
        <textarea id="description" placeholder="Enter description"></textarea>
        <br>
        <button type="submit">Upload</button>
    </form>


<script>
// Function to resize image
function resizeImage(file, maxWidth, maxHeight) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(event) {
            const img = new Image();
            img.src = event.target.result;
            img.onload = function() {
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    }
                } else {
                    if (height > maxHeight) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }
                }

                const canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;

                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, width, height);

                canvas.toBlob((blob) => {
                    resolve(blob);
                }, file.type);
            };
        };
        reader.onerror = function(error) {
            reject(error);
        };
    });
}

const uploadForm = document.getElementById('uploadForm');
const imageFileInput = document.getElementById('imageFile');
const descriptionInput = document.getElementById('description');


uploadForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const imageFile = imageFileInput.files[0];
    const description = descriptionInput.value;

    if (!imageFile || !description) {
        alert('Please select an image and enter a description.');
        return;
    }

    try {
        // Resize image
        const resizedImage = await resizeImage(imageFile, 600, 600);

        // Upload resized image to Firebase Storage
        const storageRef = storage.ref();
        const imageRef = storageRef.child(imageFile.name);
        const uploadTaskSnapshot = await imageRef.put(resizedImage);

        // Get download URL for the image
        const imageUrl = await uploadTaskSnapshot.ref.getDownloadURL();

        // Save data to Firestore
        await firestore.collection('images').add({
            imageUrl: imageUrl,
            description: description,
            createdAt: firebase.firestore.FieldValue.serverTimestamp()
        });

        alert('Image and description uploaded successfully.');
        uploadForm.reset();
    } catch (error) {
        console.error('Error uploading image and description:', error);
        alert('An error occurred while uploading image and description. Please try again.');
    }
});
</script>


    <h2>Image Gallery</h2>
    <div id="imageGallery"></div>

    <script src="app.js"></script>

<style>
 .thumbnail {
    max-width: 70px;
    max-height: 70px;
    display: block;
    margin-bottom: 10px;
}

.image-container {
    width: calc(100% / 6); /* Mengatur lebar kolom menjadi 1/6 dari lebar layar */
    box-sizing: border-box; /* Memastikan lebar termasuk padding dan border */
    padding: 5px; /* Padding antara setiap gambar */
    float: left; /* Membuat gambar mengambang ke kiri untuk membentuk grid */
}
  
.image-table {
    width: 100%;
    border-collapse: collapse;
}

.image-table td {
    padding: 10px;
    border: 1px solid #ddd;
    width: calc(100% / 2); /* Mulai dengan 2 kolom di layar besar */
}

@media screen and (max-width: 800px) {
    .image-table td {
        width: calc(100% / 3); /* Pindah ke 3 kolom di layar medium */
    }
}

@media screen and (max-width: 600px) {
    .image-table td {
        width: calc(100% / 4); /* Pindah ke 4 kolom di layar kecil */
    }
}

@media screen and (max-width: 480px) {
    .image-table td {
        width: calc(100% / 6); /* Pindah ke 6 kolom di layar sangat kecil */
    }
}


</style>

<script>
// Function to fetch images and descriptions from Firestore
async function getImages() {
    const snapshot = await firestore.collection('images').get();
    return snapshot.docs.map(doc => doc.data());
}

// Function to display images and descriptions in a table
// Function to display images and descriptions in a table
async function displayImages() {
    const images = await getImages();
    const imageGallery = document.getElementById('imageGallery');

    images.forEach(image => {
        const container = document.createElement('div');
        container.classList.add('image-container');

        const thumbnail = document.createElement('img');
        thumbnail.src = image.imageUrl;
        thumbnail.alt = 'Thumbnail';
        thumbnail.classList.add('thumbnail');
        container.appendChild(thumbnail);

        const description = document.createElement('p');
        description.textContent = image.description;
        container.appendChild(description);

        imageGallery.appendChild(container);
    });
}

// Display images when the page loads
window.addEventListener('load', () => {
    displayImages();
});


</script>


Code diatas menggunakan thumbnail dan resize file menjadi maksimal 600px agar ukuran file size tidak besar

Copy paste kode dibawah ini dan tempel di Theme/Custom Edit html dibawah <head>dan simpan
  <script src='https://cdn.jsdelivr.net/npm/lightgallery/dist/js/lightgallery.min.js'/>
  <script src='https://cdn.jsdelivr.net/npm/lg-thumbnail/dist/lg-thumbnail.min.js'/>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'/>
  <script src='https://www.gstatic.com/firebasejs/9.0.2/firebase-app-compat.js'/>
  <script src='https://www.gstatic.com/firebasejs/9.0.2/firebase-auth-compat.js'/>
  <script src='https://cdn.jsdelivr.net/npm/sweetalert2@10'/>
  <script src='https://www.gstatic.com/firebasejs/9.6.1/firebase-storage-compat.js'/>
  <script src='https://www.gstatic.com/firebasejs/9.6.0/firebase-firestore-compat.js'/>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js' type='text/javascript'/>
  <script src='//cdn.firebase.com/js/client/2.2.1/firebase.js' type='text/javascript'/>

    <!-- Include Firebase SDK -->
    <script>
        // Masukkan kode firebaseConfig dibawah ini
  const firebaseConfig = {
  apiKey: &quot;AIzaSy....&quot;,
  authDomain: &quot;karirid...com&quot;,
  databaseURL: &quot;https://.....&quot;,
  projectId: &quot;karir...&quot;,
  storageBucket: &quot;karir....com&quot;,
  messagingSenderId: &quot;...&quot;,
  appId: &quot;1:843...:web:063...&quot;,
  measurementId: &quot;G-5...&quot;
};
      
  // Inisialisasi Firebase
  firebase.initializeApp(firebaseConfig);

  // Mendapatkan referensi Firestore
  const firestore = firebase.firestore();
      
  // Mendapatkan referensi autentikasi Firebase
  const auth = firebase.auth();
      
const storage = firebase.storage();
      </script>
Perhatikan kode agar disesuaikan dengan project firebase anda

    <!-- Include Firebase SDK -->
    <script>
        // Masukkan kode firebaseConfig dibawah ini
  const firebaseConfig = {
  apiKey: &quot;AIzaSy....&quot;,
  authDomain: &quot;karirid...com&quot;,
  databaseURL: &quot;https://.....&quot;,
  projectId: &quot;karir...&quot;,
  storageBucket: &quot;karir....com&quot;,
  messagingSenderId: &quot;...&quot;,
  appId: &quot;1:843...:web:063...&quot;,
  measurementId: &quot;G-5...&quot;
};
diganti dengan script pemberian Firebase

Masuk ke Firebase anda dan ke Project anda kemudian pilih menu firestore database
Ubah Rule dengan kode berikut:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Aturan untuk koleksi "users"
    match /users/{document=**} {
      allow create: if request.auth != null;
      allow read, update, delete: if request.auth != null;
    }

    // Aturan untuk koleksi "data"
    match /data/{document=**} {
      allow read, write: if request.auth != null;
    }
   // Aturan untuk koleksi "images"
    match /images/{document=**} {
      allow read, write;
    }
       // Aturan untuk koleksi "images"
    match /databaru/{document=**} {
      allow read, write;
    }
     match /dataide/{document=**} {
      allow read, write;
    }
  }
}

Ubah Rule untuk Storage dengan kode berikut:

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read;
      allow write: if request.resource.size < 5 * 1024 * 1024 // 5 MB
                    && request.resource.contentType.matches('image/.*');
    }
  }
}

ingat bahwa Server hanya membatasi gambar dengan ukuran maksimal 5Mbs
Berikut hasil penyimpanan foto/gambar/image di storage firebase
Dan SELESAI

Lihat Demo
Jika ada pertanyaan silahkan gunakan komentar dibawah

Post a Comment