Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Upload file (image) by .put() method to firebase-storage get unexpected result

I’m newbie of Firebase, specially Firebase-storage. I’m trying follow [Firebase-storage upload files docs][1].

When try to upload file (i try a .jpg image file) from URL (get URL from <input tag and method URL.createObjectURL(event.target.files[0])) use .put() method, Firebase-storage was updated, but have a problem: size of this image just 9 Bytes (B), can’t preview in Storage and can’t render to <img tag of browser. I rendered this .jpg image files with .getDownloadURL() method as [Firebase-storage download files docs][2]. This is 2 image of result [Upload with .put() method – result in Storage conslole][3] and [Upload with .put() method – result in browser][4]

In the other hand, when i upload the same files above (.jpg image file) manually – use Upload File button in Storage console, size of this file in Storage console is 79.98 Kilobytes (KB), i can preview in Storage console and can render to <img tag with [.getDownloadURL()][2] method too. This is 2 image of result: [Upload manually with Upload File button – result in Storage conslole][5] and [Upload manually with Upload File button – result in browser][6]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And now is code of .put() method in ProcessImage.js file (i think problem was produced in this file)

import { useState } from "react";
import { storage } from "./firebaseConfig";
import "firebase/storage";

function ProcessImage() {
  const [imgURL, setImgURL] = useState("");
  
  // Create a storage reference from our storage service
  var storageRef = storage.ref();

  // Create a reference to feeds1_avata_icon.jpg
  var flagRef = storageRef.child("feeds1_avata_icon.jpg");

// After choose image, immediately put this image to Firebase-storage
  function loadImg(event) {
    // get file from input
    var file = URL.createObjectURL(event.target.files[0]);

    // put file to storage
    flagRef
      .put(file, {
        contentType: "image/jpeg",
      })
      .then((snapshot) => {
        console.log("Uploaded a blob or file!");
      });
  }

// if click button, render image from Firebase-storage to <img tag
  function handleDownload() {
    flagRef.getDownloadURL().then((url) => {
      setImgURL(url);
    });
  }

  return (
    <div>
      <input type="file" id="uploadFile" onChange={(e) => loadImg(e)} />
      <img src={imgURL} alt="" id="image" />
      <input type="button" value="Button" onClick={handleDownload} name="" />
    </div>
  );
}
export default ProcessImage;

Next is my firebaseConfig.js file:

import firebase from "firebase/app";
import "firebase/firestore"; 
import 'firebase/auth'
import 'firebase/storage'

const firebaseConfig = {
  apiKey: "AIzaSyBU8gkh5H0NwfTTbZ-VQNaF8lAcdkyV31Y",
  authDomain: "facebook-clone-f4938.firebaseapp.com",
  projectId: "facebook-clone-f4938",
  storageBucket: "facebook-clone-f4938.appspot.com",
  messagingSenderId: "584659342846",
  appId: "1:584659342846:web:b1b19535364ca4f1e6dcaf",
  measurementId: "G-FQH967H0YJ",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const providers = new firebase.auth.GoogleAuthProvider();
var storage = firebaseApp.storage()
export { auth, providers, storage };
export default db;

Some information about version in package.json:

"name": "facebook-clone-2.0",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.8.2",
    "@emotion/styled": "^11.8.1",
    "@firebase/storage": "^0.9.4",
    "@mui/icons-material": "^5.5.1",
    "@mui/material": "^5.5.2",
    "@testing-library/jest-dom": "^5.16.3",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "antd": "^4.19.5",
    "firebase": "^8.10.1",
    "lodash": "^4.17.21",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "react-with-firebase-auth": "^1.4.1",
    "web-vitals": "^2.1.4"

This problem i get when run ReactJs app in localhost. Now i’m stuck i got no idea. Thanks for all help!
[1]: https://firebase.google.com/docs/storage/web/upload-files?hl=en&authuser=0
[2]: https://firebase.google.com/docs/storage/web/download-files?hl=en&authuser=0
[3]: https://i.stack.imgur.com/2cCU6.jpg
[4]: https://i.stack.imgur.com/PDOXa.jpg
[5]: https://i.stack.imgur.com/FJDve.jpg
[6]: https://i.stack.imgur.com/GKJXv.jpg

>Solution :

You can pass the File object directly into put() that takes a blob or ArrayBuffer as first parameter. There’s no need to create an object URL for the same.

flagRef.put(event.target.files[0])

You should also check if the user has actually selected a file or not. Try refactoring the code as shown below:

function loadImg(event) {
  // get file from input
  const file = event.target.files[0];

  if (file) {
    // put file to storage
    flagRef
      .put(file, {
        contentType: "image/jpeg",
      })
      .then((snapshot) => {
        console.log("Uploaded a blob or file!");
      });
  } else {
    alert("Please select a file")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading