Photo by Jan Antonin Kolar on Unsplash

Files in the Blockchain

Angel Java Lopez
2 min readFeb 16, 2021

--

These days I am practicing programming smart contracts in Solidity using TDD. There are several projects I am working on: some DeFi projects, a programmatic faucet, user login and onboarding, personal notes, some games. One of the projects already has something to show: I have been able to upload (image) files to RSK’s testnet.

One comment: a blockchain is not the more appropriate place to save files, at least an Ethereum-like. The upload of a file could cost many millions of gas units. And the retrieval is not the fastest. But I wanted to explore some Solidity code, and also, do an experiment with web application.

Show Me The Code

The project is at https://github.com/ajlopez/SimpleFS

The main contract I’m using is ChunkedFile.sol. It can contains an array of chunks. Each chunk is a bytes array. The owner of the contract can upload a file, putting chunks into this smart contract. The chunks can be retrieved by anyone, one by one.

The internal state is very simple:

contract ChunkedFile {
address public owner;

bytes[] public chunks;

There are functions for put and get chunks:

function get(uint nchunk) public view returns (bytes memory) {
return chunks[nchunk];
}
function put(uint nchunk, bytes memory content) public onlyOwner {
if (nchunk == chunks.length)
chunks.push(content);
else
chunks[nchunk] = content;
}

Uploading and Downloading Files

As in other of my projects, I added commands that use my RskApi library (read Command Line Tools for RSK). Detailed instructions at https://github.com/ajlopez/SimpleFS/tree/master/commands

Having defined the host and some user with balance, you can upload a file (I recommend to use a file with size less than 20K) using a chunk size of 4096 bytes:

node deploy myuser file1 ChunkedFile
node upload myuser file1 <localfilepath> 4096

To download the file, execute

node download myuser file1 <localfilepath>

Viewing Files

I wrote an express web application, that you can run locally (read instructions). It has an index with six images, and one page to show each one.

One of my watercolor painting practice, now immortalized in the blockchain

Next Steps

  • A next.js web application
  • Deploy the sample dapp to a hosting service (maybe vercel)
  • Use of directories
  • Add properties to files and directories

I had a lot of fun with this project!

Angel “Java” Lopez
@ajlopez

--

--