Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the image url from IPFS info in React.js?

I've gotten this IPFS info such as "/ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE" as API response.

I want to display this file(image) on my page, but I can't find out the correct solution.

How can I get the image URL from this info in react app?

Please help with my concern.

like image 691
cocoa Avatar asked Dec 05 '25 06:12

cocoa


2 Answers

Try adding https://ipfs.io in the beginning of your ipfs info as suggested in this document https://docs.ipfs.io/concepts/what-is-ipfs/

i.e

ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE

becomes

https://ipfs.io/ipfs/QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE
like image 159
Akshay Mathur Avatar answered Dec 07 '25 21:12

Akshay Mathur


If you're using js-ipfs, you can retrieve the image over IPFS, and display it:

/** Uses `URL.createObjectURL` free returned ObjectURL with `URL.RevokeObjectURL` when done with it.
 * 
 * @param {string} cid CID you want to retrieve
 * @param {string} mime mimetype of image
 * @param {number} limit size limit of image in bytes
 * @returns ObjectURL
 */
async function loadImgURL(cid, mime, limit) {
    if (cid == "" || cid == null || cid == undefined) {
        return;
    }
    const content = [];
    for await (const chunk of ipfs.cat(cid, {length:limit})) {
        content.push(chunk);
    }
    return URL.createObjectURL(new Blob(content, {type: mime}));
}

Then you can display it with something like:

<body>
<img id="myImage" />
<script>
async function setImage() {
    // just an example, make sure to free the resulting ObjectURL when you're done with it
    //
    // if your CID doesn't work, try this one: Qmcm32sVsMYhURY3gqH7vSQ76492t5Rfxb3vsWCb35gVme
    // that's a popular CID, which should resolve every time
    document.getElementById("myImage").src = await loadImgURL("QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE", "image/png", 524288);
}
setImage();
</script>
</body>

The big advantage of this is you're using the IPFS network itself, and not relying on a public HTTP gateway (the recommended way).

like image 35
Discordian Avatar answered Dec 07 '25 21:12

Discordian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!