Retrive JPG image stored on IPFS using Infura API and ipfs-http-client in React

8.1k views Asked by At

I uploaded a jpg image on ipfs using infura API and ipfs-http-client. The file was taken from input with type=file. The event listner was onchange.

// imports
const IpfsHttpClient = require("ipfs-http-client");
const ipfsC = IpfsHttpClient({
  host: "ipfs.infura.io",
  port: "5001",
  protocol: "https",
});

<input type="file" onChange={(e) => { upload(e); }} />

  const upload = async (e) => {
    const file = e.target.files[0];
    const added = await ipfsC.add(file, {
      progress: (prog) => console.log(`received: ${prog}`),
    });
    console.log(added)
  };

the hash that I get back is QmQnSWbsck26xrFRiowdV2JhP7cbKRc9KbjWinRhmJgiMa.Now I am trying to retrieve the image and display it on the web app. How should I proceed further.

2

There are 2 answers

1
Dietrich Ayala On BEST ANSWER

This is a v0 CID. You can learn more about CIDs and the different versions in the IPFS docs here.

You can view more information about the encoding information with the CID inspector:

https://cid.ipfs.io/#QmQnSWbsck26xrFRiowdV2JhP7cbKRc9KbjWinRhmJgiMa

Or you can load it via HTTP from an IPFS gateway. There are many of those, some listed here at the IPFS Public Gateway Checker.

You can load via any gateway - however, note that the gateway can see what you are requesting!

The best and safest way to use IPFS HTTP gateway URLs is by getting the v1 CID which is encoded in a way that works with how HTTP URLs work. It also ensures origin-based security (in case it's an HTML URL and executes code).

So in your code where you have the variable added, you can do this:

let v1CID = added.cid.toV1()

In your case that value will be:

bafybeibekkxkexvbw65ma4syafzfnxtumfx7wjkbtaf2zfsoypmshn6ccu

You can now construct a URL to a gateway like:

https://bafybeibekkxkexvbw65ma4syafzfnxtumfx7wjkbtaf2zfsoypmshn6ccu.ipfs.dweb.link

And you can use that URL in an tag, for example.

Look at the public gateway checker above to view other options like CloudFlare's gateway, which support this subdomain URL feature.

0
Rahul Bera On
function toBase32(value) {
    var cid = new CID(value)
    return cid.toV1().toBaseEncodedString('base32')
  }

this converts the given v0 hash to v1 hash. And then the image can be retrieved as mentioned by Dietrich Ayala in the above answer.