Supabase Storage Image Upload Tutorial Using Ionic React & Capacitor Camera

aaronksaunders

Aaron K Saunders

Posted on August 24, 2021

Supabase Storage Image Upload Tutorial Using Ionic React & Capacitor Camera

This is a post to support the video I did on the same topic. The video was split into two parts, one covering setting up Ionic Framework in ReactJS to work with the Capacitor Camera Plugin, and the other part was to upload the image captured from the camera to Supabase Storage.

The Video

Uploading the Camera Image

All of the magic happens here

 /**
   * upload to storage bucket, convert path to blob
   * get file name from path
   * 
   * @param path
   */
  const uploadImage = async (path: string) => {
    const response = await fetch(path);
    const blob = await response.blob();

    const filename = path.substr(path.lastIndexOf("/") + 1);

    const { data, error } = await supabase.storage
      .from("image-bucket")
      .upload(`${filename}`, blob, {
        cacheControl: "3600",
        upsert: false,
      });

    if (error) alert(error?.message);

    console.log(data);

    getAllImages();


    return true;
  };
Enter fullscreen mode Exit fullscreen mode

We take the webPath from the Capacitor Camera Plugin and use fetch to get a blob which we then upload to supabase.

Downloading the Image From Supabase

What I do here is create a seperate component RenderImage and in the initial useEffect hook, I make an API call to supabase to get the publicURL of the image and set it to a local state variable, when the variable is set, the image is drawn to the screen.

const RenderImage: React.FC<any> = ({ path }) => {
  const [publicUrl, setPublicUrl] = useState<any>("");
  useEffect(() => {
    (async () => {
      const { publicURL } = supabase.storage
        .from("image-bucket")
        .getPublicUrl(path);

      setPublicUrl(publicURL);
    })();
  },[path]);

  return <IonImg src={publicUrl} />;
};
Enter fullscreen mode Exit fullscreen mode

All The Rest...

the rest of the video is a more detailed explanation of the supabase api and how you need to setup the buckets for use.

Source Code

💖 💪 🙅 🚩
aaronksaunders
Aaron K Saunders

Posted on August 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related