DEV Community

Berkay
Berkay

Posted on • Originally published at raufsamestone.com

How to send an image from Unsplash to IPFS?

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 IPFS using ipfs-http-client and Nextjs

You can see the demo here or jump to directly GitHub

Demo

Pre-requests

  • Node 15 >

Getting started

Create a simple next js app:

npx create-next-app ipfs
Enter fullscreen mode Exit fullscreen mode

Add IPFS HTTP client library using yarn:

yarn add ipfs-http-client
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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);
});
}
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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);
}
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)