簡體   English   中英

在反應前端動態顯示上傳到 ipfs 的圖像

[英]display image uploaded to ipfs dynamically in react frontend

我實現了下面的代碼,但是當我點擊保存時它返回 ipfs hash 但上傳的圖片沒有顯示在首頁上。 請任何幫助將不勝感激!

onSubmit = async (event) => {
    event.preventDefault();
    console.log('The file will be Submitted!');
    let data = this.state.buffer;
    console.log('Submit this: ', data);
    if (data){
      try{
        const postResponse = await ipfs.add(this.state.buffer) 
        console.log("postResponse", postResponse);
              
      } catch(e){
        console.log("Error: ", e)
      }
    } else{
      alert("No files submitted. Please try again.");
      console.log('ERROR: No data to submit');
    }
   
  }

您必須使用返回的 CID hash 來構建有效圖像 URL。因為<img/>標簽不支持ipfs:// URL 方案,您將不得不依賴 HTTP 網關之一,如ipfs.iodweb.link如下:

https://{gateway URL}/ipfs/{content ID}/{optional path to resource}

所以你可以像這樣使用<img/>標簽顯示圖像:

const Comp = () => {
  const [cid, setCid] = useState("");

  // logic to retrieve and set CID state

  return (
    <img src={`https://ipfs.io/ipfs/${cid}`} />
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM