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:
npmiethstorage-sdk
Step 2: Manage Files
2.1 Create FlatDirectory
In this section, you will create a FlatDirectory contract for managing files.
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 callclose() 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 callclose() on your SDK instances to release internal Workers and threads. Failing to do so may prevent Node.js from exiting normally.
// Close the standard SDK instance (used for uploading and downloading)
await flatDirectory.close();
console.log("Standard SDK instance closed.");
// If you created a download-only SDK instance, make sure it is also closed
await downloadOnlySDK.close();
console.log("Download-only SDK instance closed.");
const key = "test.txt";
// Optional: only needed if downloading immediately after uploading
// await new Promise(resolve => setTimeout(resolve, 5000));
const data = await ethStorage.read(key);