DEV Community

Cover image for Appwrite storage service
Azamah Jr
Azamah Jr

Posted on

Appwrite storage service

Appwrite is an open-source, self-hosted Backend-as-a-Service which provides a suite of SDKs and APIs to facilitate development on any platform. In this article we are going to look at Appwrites' Storage service and API which lets you manage your project files

Appwrites storage service grants read and write permissions to manage access to every file in storage, this lets authenticated users upload, download, view and query and manage all project files.

Storage can be managed and manipulated in two ways;

  • Using Appwrites console
  • Using Appwrites storage API, which provides various endpoints to manipulate files in storage

To demonstrate Appwrites storage service, in this article we will be utilizing Appwrites storage API to manage and manipulate images files in our demo react app

Prerequisites

  • This article assumes you have appwrite installed, if you don't heres an article to get you started
  • Basic knowledge of javascript and react

About the demo app

The front end of the app has been pre built, and in this article we would focus only on implementing functionality in the app using Appwrite as our backend and Appwrites storage API. The following functionalities;

  • Upload an image to storage
  • Delete an image
  • Get and Display all images we currently have stored
  • Download stored images
  • For this demo we want to provide authentication so users can have permissions to read and write to storage , but we want to keep it simple here so we are going to implement an Anonymous login using Appwrites createAnonymousSession() method , where users can create an account without providing information such as an email address, username or password.

Implementing each of the above functionalities we will be utilizing endpoints from the storage API, and as such we will gain hands on experience in utlizing the storage API in a real word scenarios.

Note: We will not cover how to build the demo app with react in this video. However i'll provide links to the projects starter files, which you can clone from github and follow along to implement functionality with Appwrite

Setup

Clone the project starter files Here to code along

Once you've cloned the project repository, navigate to the project folder and run the following command in the projects root to install the projects dependencies

npm install
Enter fullscreen mode Exit fullscreen mode

Create new Appwrite project

In Appwrites console, create a new project and name it purp-flower.

In the project we just created, click the add platform button and add a web platform so we can initialize the web SDK and interact with Appwrite services in our react app

Configuring Appwrite

In the project root, run the following command to add Appwrite to the project

npm install appwrite --save
Enter fullscreen mode Exit fullscreen mode

First up, lets import the Appwrite module, navigate to src/appwrite/appwrite.congfig.js and enter the following code

// Import the Appwrite module
import { Appwrite } from "appwrite";
Enter fullscreen mode Exit fullscreen mode

The next step is to initialize our web SDK with our project ID and our Appwrite endpoint, which can both be found in the project settings page in the Appwrite console

// Init your Web SDK
const appwrite = new Appwrite();

appwrite
    .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
    .setProject('455x34dfkj') // Your project ID
;

export const storage = appwrite.storage
export const account = appwrite.account

Enter fullscreen mode Exit fullscreen mode

Ok lets begin implementing our apps functionality

Uploading images & Anonymous login

Before a user can be permitted to upload an image to storage, they have to be authenticated, as earlier mentioned we will implement anonymous login to authenticate users without requiring usernames and passwords

Uploading a file to storage using the web SDK requires the storage.createFile() method. This method requires three parameters: a file, an array of strings to define the read permissions, and an array of strings to define write permissions.

In the src/app.js file in the project, lets create an uploadImage() function, copy the code below.

// 1. Upload images to appwrite
  const uploadImage = async (e) => {
    e.preventDefault();

    try {
      // Checks if user is logged in current session
      const user = await account.getSession("current");

      for (let i = 0; i < image.length; i++) {

        if (user) {
          // Upload image
          await storage.createFile(image[i], ["*"], ["*"]);
          console.log('Image uploaded successfully!');
          window.location.reload(); // Reloads window on upload
        } else {
          // Create anonymous user
          await account.createAnonymousSession();
          await storage.createFile(image[i], ["*"], ["*"]);
          console.log('New user was created ');
          window.location.reload();
        }
      }

    } catch (error) {
      console.log(`${error.message}`);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Lets take a closer look at the storage.createFile()method

storage.createFile(image[i], ["*"], ["*"])
Enter fullscreen mode Exit fullscreen mode

The first parameter of this method is an image within an array of images, the second parameter defines the read parameters, setting the array of strings to and asterisks, grants read access to all users no matter their role. We can restrict this access to users of certain roles. The third parameter defines the write permissions, and like the read permission, all users of the application have been granted write access

Next we get the currently logged in user, if there exist a logged in user, we upload the image file to storage and if the user isn't authenticated and logged in, we call the account.createAnonymousSession which creates and logs in an anonymous user. Once thats done, we then upload the image.

Now go ahead and upload a couple of images to storage using the demo app
Appwrite storage API demo app by Azamah Jr

We can check to see if our images were uploaded to storage using Appwrites console, and as you can see below the images were uploaded

Appwrite storage console

Getting a list of all images in storage

To get a list of all images we have in storage we require the use of the storage.listFiles() method, once we get the list we will store it in an imageList state. Copy the code below to implement the getAllStoredImg()function

const getAllStoredImg = async () => {
    const images = await storage.listFiles();
    console.log(images)
    setImageList(images.files);

};
Enter fullscreen mode Exit fullscreen mode

We would want our application to get the list of all images in storage each time the app reloads, the code below implements that

 useEffect(() => {
    getAllStoredImg();
  }, []);
Enter fullscreen mode Exit fullscreen mode

Now we have a list of all images currently in storage, next lets display the images, we need to use the storage.getFilePreview(imgID) method, and would take an image ID as parameter.

As we probably have a lot of images stored, we therefore loop through the imageList state to get each image ID from the list and parse that as a parameter to the storage.getFilePreview()method to preview the image, how this was done with react is beyond the scope of this article

At this point the demo app should look like this:

Appwrite storage API demo app - Azamah jr

As you can see, we are getting and displaying all the images we had stored. Next lets implement the delete and download features

Delete an image

Deleting an image requires the use of storage.deleteFile()method, as a parameter we pass in the image Id of the image in storage which we want deleted

// 2. Delete an image
   const deleteImage = async (e, imgId) => {
    e.preventDefault();

    try {
      await storage.deleteFile(imgId);
      window.location.reload();
      console.log("Image Deleted Successfully");
    } catch (error) {
      console.log(`${error.message}`);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Download an image

To download an image from storage we require the use of storage.getFileDownload(imgID)method, this method takes the image ID as a parameter

const downloadImage = (e, imgId) => {
    e.preventDefault();

    try {
      const downloadLink = storage.getFileDownload(imgId);
      window.open(downloadLink.href);
    } catch (error) {
      console.log(`${error.message}`);
    }
 };
Enter fullscreen mode Exit fullscreen mode

Conclusions

We've implemented all the functionalities of our demo app, i am glad you made it this far. if you have any questions let me know down in the comments

Here are some links if you want to learn more on the Appwrite features which were implemented in this article;

Thanks for reading, thats all for now ✌️

Top comments (0)