How to send an image from Unsplash to IPFS?

Berkay Demirbas
2 min readMar 28, 2022

I suggest you include the web3 environment in your growth strategy. Therefore, you should use technical implementations decentralized networks like subgraph or IPFS.

In this guide, you’ll learn how to send image files to using ipfs-http-client and Nextjs

You can see the demo here or jump to directly GitHub

Pre-requests

  • Node 15 >

Getting started

Create a simple next js app:

npx create-next-app ipfs

Add IPFS HTTP client library using yarn:

yarn add ipfs-http-client

Create a new constant for IPFS gateway. In this case, we will use Infura API.

const client = create("https://ipfs.infura.io:5001/api/v0");

Get a random image URL from Unsplash. You can see more detail in here.

async function getImage() {
fetch(https://source.unsplash.com/500x500/?beach).then((response) => {
let imageURL = response.url;
setImageURL(imageURL);
});
}

Or you can use your own fetching solution like custom form data, Cloudinary etc.

Then upload your file to IPFS.

The critical thing is, you should fetch the image URL as a blob object.

const blobFile = await fetch(imageURL).then((r) => r.blob());

Create a new function as uploadFile

async function uploadFile() {
const blobFile = await fetch(imageURL).then((r) => r.blob());
try {
const added = await client.add(blobFile);
const url = https://ipfs.infura.io/ipfs/${added.path};
updateIPFSURL(url);
} catch (error) {
console.log("Error uploading file: ", error);
}
}

Finally, you are ready to fetch and image image object from URL and send to IPFS.

Clone the full repository here and run;

yarn dev

You can see the more detailed cases about Web3 from Nader Dabit’s posts here.

Thanks for reading. 👋 Don’t forget to subscribe me on Medium or Dev.to

Originally published at raufsamestone.com on March 28, 2022.

--

--