Upload Your Files to Filebase from your CLI
Tags: blockchain, ipfs, tutorial, aws
Published: 2023-04-07 14:14:24

If you are building a decentralized App, in most cases you need to store your images, files, videos on a decentralized platform like IPFS, File coin or Filebase ,so in this blog we will discuss how you can upload your files to File-base.
  
Before jumping to code, first lets discuss what is decentralized storage?

So As per name, Decentralized storage means it is not centralized and all of your data is not stored at some data-center that is controlled by some few. In Decentralized storage,
users can store their data regardless of centers. This system uses peer-to-peer network-model to achieve decentralization.

- IPFS[Inter Planetary File System] is a peer-to-peer hypermedia protocol designed to store and share data in a decentralized manner.[Know about IPFS](https://ipfs.io/)
 
- File-base is the first S3-compatible object storage platform that allows you to store data.[More about File-base](https://filebase.com/)

So let us  start our journey to uploading files to file-base.

Here, we are going to upload files using the command-line , in the next blog I will show how you can do this with user-input and with a cool front-end.  

Prerequisites:

- NodeJS installed on your Machine
[If not you can install from here [Download NodeJS](https://nodejs.org/en/download/)]

-A File-base Account [You can create-one for free](https://console.filebase.com/signup)

-A basic knowledge of JavaScript(of course not mandatory)

So Let's start.

1) Open your Terminal and run this command
```
mkdir filebaseupload-demo
cd filebaseupload-demo
```
This will create a new folder named **filebaseupload-demo **by cd command we will enter in our folder.

2) Run following command
```
npm init -y
```
This will create a package.json

3) Now open our folder **filebaseupload-demo** with your code editor(VS-Code, Sublime, Atom or Whatever you use)

I prefer to use VS-Code.

At this Point your Folder-structure should look like this.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o29p8p9i1iw2j0lvazeg.jpg)

4)Now create a file named `index.js`

5)As we are using File-base's S3 compatible API, We need to add some dependencies
Now Open Your Terminal in VS Code and run following commands
```
npm install aws-sdk dotenv fs
```  
This will install

- `aws-sdk` : aws-sdk for interacting with aws-services throught Javascript
- `dotenv` : loads our environment variable from .env to `process.env.VARIABLE_NAME`
- `fs` : packge used to read and write files 


6) Now, create a **.env** file in our root directory 

Now in .env file add environment variable that we need 
```
AWS_ACCESS_KEY_ID=YOUR_ACCES_KEY_FROM_FILEBASE
AWS_SECRET_ACCESS_KEY=YOUR_ SECRET_KEY_FROM_FILEBASE
BUCKET_NAME=YOUR_FILEBASE_BUCKET_NAME
```
Here is a guide you can get your keys:

- Go to [Filebase console](https://console.filebase.com/) and sign-in
 
Now log-in with your account 
On successful login you should see screen like this


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16ihh0wxl5mghqztakqk.jpg)

Now Click on Buckets in left-sidebar.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihqsb2wq126f1rcgbhw5.png)

Now click on create bucket


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qmilqq5tv66l6o6rvqg4.png)

Now Enter bucket name `demo-upload` and click on `create-bucket` button


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18vflj83fc01l9fxaf8q.jpg)


Now click on bucket name

Now click on Access Keys in Sidebar and you should see your keys



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oo4hmfgfe5evj2mixeu1.png)

Now,

-  copy KEY and paste at YOUR_ACCES_KEY_FROM_FILEBASE in .env

- copy SECRET and paste at YOUR_ SECRET_KEY_FROM_FILEBASE in .env

- in BUCKET_NAME write our bucket name in our case it is `demo-upload`






7) Now Open your  `index.js` and paste this code
```
require('dotenv').config();
const AWS = require("aws-sdk");
const fs = require("fs");
const s3 = new AWS.S3({
    endpoint: 'https://s3.filebase.com',
    region: 'us-east-1',
    signatureVersion: 'v4'
});
fs.readFile('BAYC.png', (err, data) => {
    if (err) {
        console.log(err);
        return;
    }
    const params = {
        Bucket: process.env.BUCKET_NAME,
        Key: 'test/BAYC.png',
        ContentType: 'image/png',
        Body: data,
    }
    const request = s3.putObject(params);
    request.on('httpHeaders', (statusCode, headers) => {
        console.log(`CID:${headers['x-amz-meta-cid']}`);
        console.log(`Go to https://ipfs.filebase.io/ipfs/${headers['x-amz-meta-cid']}`);
    });
    request.send();
})
```

Now Lets under-stand our code:
```
require('dotenv').config();
const AWS = require("aws-sdk");
const fs = require("fs");
```
Here, We are importing our aws-sdk and fs module.
```
const s3 = new AWS.S3({
    endpoint: 'https://s3.filebase.com',
    region: 'us-east-1',
    signatureVersion: 'v4'
});

```
This will create a new instance of aws's  S3-storage service
with given configuration endpoint.

```
fs.readFile('BAYC.png', (err, data) => {
    if (err) {
        console.log(err);
        return;
    }
```
Here we are reading our file in our directory which is [BAYC Image](https://ipfs.filebase.io/ipfs/Qma9YuNh8x8V6QxP6VHvma1tAZP5BJqdMvqnyZqJizyJFt) to upload on File-base.
We are using fs modules's readfile method to read the file

```
 const params = {
        Bucket: process.env.BUCKET_NAME,
        Key: 'test/BAYC.png',
        ContentType: 'image/png',
        Body: data,
    }
    const request = s3.putObject(params);
```

Now we have read the file.

We are declaring our parameters of object with Bucket-name, Key[Where to store file in bucket],Content type of image, and Body.

After that we are calling s3's pubObject method with our parameters

```
 request.on('httpHeaders', (statusCode, headers) => {
        console.log(`CID:${headers['x-amz-meta-cid']}`);
        console.log(`Go to https://ipfs.filebase.io/ipfs/${headers['x-amz-meta-cid']}`);
    });
request.send();
```
request.on() is function that listens to events emitted by remote server.

When our remote server sends the httpHeaders, the listener function is called 
and inside that we are logging our CID by using headers['x-amz-meta-cid]
and we are generating link for our file by 
`https://ipfs.filebase.io/ipfs/${headers['x-amz-meta-cid']}`

Note that In console.log we are using `  `` Backticks` (template literals ) and not regular 
` ""` double quotes.

Now lets run our file
go to terminal and run `node index.js`

If everything goes ok, you should see output  like this


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5s7ifcxz273jr7nu4d8.jpg)
  
If you copy the link and paste it in browser you should see the image.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q9gxrcj2tety2nz7h4l8.jpg)
Now if you go to your file-base and navigate to your bucket you should see the image is uploaded there


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utbf4qxyij193mi33wcv.jpg)

If you see ,take a minute and reward you-self that you followed the entire blog
 
Until next
Keep coding ,
Keep debugging


Feel free to contact me
 [![Github](https://img.shields.io/badge/Github-%231DA1F2.svg?logo=Github&logoColor=black)](https://github.com/VIVEK-SUTHAR) [![LinkedIn](https://img.shields.io/badge/LinkedIn-%230077B5.svg?logo=linkedin&logoColor=white)](https://linkedin.com/in/VIVEK_SUTHAR) [![Twitter](https://img.shields.io/badge/Twitter-%231DA1F2.svg?logo=Twitter&logoColor=white)](https://twitter.com/theviveksuthar)