![](/img/trans.png)
[英]How can I pass image url from parent component to child component via props [REACT.JS]
[英]How can I get the image url from IPFS info in React.js?
我已經得到了這個 IPFS 信息,例如“/ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE”作為 API 響應。
我想在我的頁面上顯示這個文件(圖像),但我找不到正確的解決方案。
如何從反應應用程序中的此信息中獲取圖像 URL?
請幫助解決我的問題。
你可以這樣做:
tokenURI.replace("ipfs://", "https://ipfs.io/ipfs/");
嘗試添加https://ipfs.io在IPF問題信息的開始,因為這個文件中提出https://docs.ipfs.io/concepts/what-is-ipfs/
如果您使用的是 js-ipfs,則可以通過 IPFS 檢索圖像,並顯示它:
/** 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 (optional, but useful)
* @param {number} limit size limit of image in bytes
* @returns ObjectURL
*/
async function loadImgURL(cid, mime, limit) {
if (cid == "" || cid == null || cid == undefined) {
return;
}
for await (const file of ipfs.get(cid)) {
if (file.size > limit) {
return;
}
const content = [];
if (file.content) {
for await(const chunk of file.content) {
content.push(chunk);
}
return URL.createObjectURL(new Blob(content, {type: mime}));
}
}
}
然后您可以使用以下內容顯示它:
<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>
這樣做的最大優點是您使用的是 IPFS 網絡本身,而不是依賴公共 HTTP 網關(推薦的方式)。
關於從 IPFS 獲取圖像,我認為在這些答案中沒有得到充分討論的一件事是,您需要
在過去的幾天里,我花了一點時間來解決這個問題,而且它總是會讓你不得不直接訪問你自己的節點。
有“網關”,它們是由社區托管的節點,您可以在此處的 IPFS 文檔中閱讀有關它們的更多信息: https://docs.ipfs.io/concepts/ipfs-gateway/#limitations-and-potential-變通方法
網關的問題是它們不應該被依賴於生產站點,如下所示。 可能有一些托管節點有人免費提供,但我對此表示懷疑,無論如何你都不想依賴它。
我認為上面的其他問題已經詳細說明了您在收到回復后如何實際處理回復,但我想在我的回答中涵蓋這個額外的基礎。
let imgUrl = url?.slice(url.indexOf(":"),url?.lastIndexOf("/"));
let slice = url?.slice(url.lastIndexOf("/"),url?.length)
let renderURL = `https${imgUrl}.ipfs.dweb.link${slice}`;
console.log(renderURL);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.