Use ethstorage-sdk to upload and download files

Introduction

In this tutorial, we will demonstrate how to upload and download files using the ethstorage-sdk tool.

The ethstorage-sdk provides APIs for file upload, download, and management.

In the following code examples, Sepolia is used by default. You can switch to other chains by specifying a different RPC endpoint, such as "https://rpc.delta.testnet.l2.quarkchain.io:8545" for the QuarkChain L2 testnet.

Step 1: Install ethstorage-sdk

You can install ethstorage-sdk by the following command:

 npm i ethstorage-sdk

Step 2: Manage Files

2.1 Create FlatDirectory

In this section, you will create a FlatDirectory contract for managing files.

const { FlatDirectory } = require("ethstorage-sdk");

const rpc = "https://rpc.sepolia.org";
// For QuarkChain L2 testnet:
// const rpc = "https://rpc.delta.testnet.l2.quarkchain.io:8545";
const privateKey = "0x...";

const flatDirectory = await FlatDirectory.create({
    rpc: rpc,
    privateKey: privateKey,
});
const contracAddress = await flatDirectory.deploy();
console.log(`FlatDirectory address: ${contracAddress}.`);
// FlatDirectory address: 0x37df32c7a3c30d352453dadacc838461d8629016

If you already have a FlatDirectory contract, you can set it.

2.2: Upload Files To FlatDirectory

In this section, you will upload some files into the FlatDirectory that you just created.

You can use Buffer to upload files.

You can also upload File objects. This applies to both browser and Node.js environments.

Browser

Node.js

2.3: Download Files From FlatDirectory

In this section, you will download files from the ethstorage network.

Standard SDK supports both uploading and downloading if created with ethStorageRpc. For read-only scenarios, you can create a download-only SDK instance without rpc or privateKey.

Note: Data may take a few seconds to sync after upload. You can wait a few seconds before downloading to ensure successful retrieval.

2.4: Close FlatDirectory SDK

After completing all uploading and downloading operations, you must call close() on your SDK instances to release internal Workers and threads. Failing to do so may prevent Node.js from exiting normally.

Step 3: Manage Blobs

3.1 Create EthStorage

In this section, you can create an EthStorage instance to interact directly with EthStorage for managing blobs.

3.2 Write Blob

Write blob data to the EthStorage network.

3.3 Read Blob

Read the written data from the EthStorage network.

3.4: Close EthStorage SDK

After completing all uploading and downloading operations with EthStorage, you must call close() on your SDK instances to release internal Workers and threads. Failing to do so may prevent Node.js from exiting normally.

Last updated