Appwrite storage service
Published: 2021-10-28 19:55:04

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](https://appwrite.io/docs/installation) 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](https://github.com/Kaid00/purp-flower.git) 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 

```shell
npm install
```

### 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

```zsh
npm install appwrite --save
```

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

```js
// Import the Appwrite module
import { Appwrite } from "appwrite";
```

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 

```js
// 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

```

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() ](https://appwrite.io/docs/client/storage#storageCreateFile)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.

```js
// 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}`);
    }
  };
```

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

```js
storage.createFile(image[i], ["*"], ["*"])
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/726i07jzz7ier44bnequ.png)


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 ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jwhgqkxsq1etczjrckl.png)

### 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()`](https://appwrite.io/docs/client/storage#storageListFiles) method, once we get the list we will store it in an imageList state. Copy the code below to implement the `getAllStoredImg()`function

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

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

```react
 useEffect(() => {
    getAllStoredImg();
  }, []);
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lrocm8457b2yniga8xki.png)

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()`](https://appwrite.io/docs/client/storage#storageDeleteFile)method, as a parameter we pass in the image Id of the image in storage which we want deleted

```js
// 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}`);
    }
  };
```


### Download an image

To download an image from storage we require the use of [`storage.getFileDownload(imgID)`](https://appwrite.io/docs/client/storage#storageGetFileDownload)method, this method takes the image ID as a parameter

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

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

### 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; 

- [Appwrites Storage Services](https://appwrite.io/docs/client/storage)
- [Appwrite Accounts API](https://appwrite.io/docs/client/account)

Thanks for reading, thats all for now ✌️