<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    狼愛上貍

    我胡漢三又回來了

    ipfs + 以太坊實例解析

    本文章的項目基于春哥的博客教程
    【IPFS + 區(qū)塊鏈 系列】 入門篇 - IPFS + Ethereum (下篇)-ipfs + Ethereum 大圖片存儲

    我個人只是作為記錄學習心得所借鑒
    項目流程

    首先調用代碼創(chuàng)建truffle項目

        truffle unbox react

    其次,要引入ipfs的api,用作圖片存儲的相關功能,我們是將圖片存儲到ipfs當中,而將所獲得圖片的hash區(qū)塊鏈之中,區(qū)塊鏈大數(shù)據(jù)成本的問題

        npm install –save ipfs-api

    安裝完畢調用complie編譯合約代碼,,以便使用web3調用合約存儲區(qū)塊鏈

        compile

    替換合約地址,這個需要將合約在以太坊部署并取得對應地址
    然后運行ipfs節(jié)點

        ipfs daemon

    啟動項目

        npm start

    就可以看到項目成功
    代碼解讀分析

    import React, {Component} from 'react'
    import SimpleStorageContract from '../build/contracts/SimpleStorage.json'
    import getWeb3 from './utils/getWeb3'

    import './css/oswald.css'
    import './css/open-sans.css'
    import './css/pure-min.css'
    import './App.css'

    const ipfsAPI = require('ipfs-api');
    const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});

    const contract = require('truffle-contract')
    const simpleStorage = contract(SimpleStorageContract)
    let account;

    /** Declaring this for later so we can chain functions on SimpleStorage.**/
    let contractInstance;
    //ipfs保存圖片方法//
    let saveImageOnIpfs = (reader) => {
      return new Promise(function(resolve, reject) {
        const buffer = Buffer.from(reader.result);
        ipfs.add(buffer).then((response) => {
          console.log(response)
          resolve(response[0].hash);
        }).catch((err) => {
          console.error(err)
          reject(err);
        })
      })
    }

    //創(chuàng)建構造函數(shù),添加狀態(tài)機變量//

    class App extends Component {
      constructor(props) {
        super(props)

        this.state = {
          blockChainHash: null,
          web3: null,
          address: null,
          imgHash: null,
          isWriteSuccess: false
        }
      }
    //程序啟動默認調用方法//
      componentWillMount() {
        //打印項目中網(wǎng)絡節(jié)點//
        ipfs.swarm.peers(function(err, res) {
          if (err) {
            console.error(err);
          } else {
            /** var numPeers = res.Peers === null ? 0 : res.Peers.length;**/
            /** console.log("IPFS - connected to " + numPeers + " peers");**/
            console.log(res);
          }
        });
        //web3設置,同時調用初始化方法//
        getWeb3.then(results => {
          this.setState({web3: results.web3})

          // Instantiate contract once web3 provided.
          this.instantiateContract()
        }).catch(() => {
          console.log('Error finding web3.')
        })
      }
        //初始化合約實例、web3獲取合約賬號以及合約實例//
      instantiateContract = () => {

        simpleStorage.setProvider(this.state.web3.currentProvider);
        this.state.web3.eth.getAccounts((error, accounts) => {
          account = accounts[0];
          simpleStorage.at('0xf6a7e96860f05f21ecb4eb588fe8a8a83981af03').then((contract) => {
            console.log(contract.address);
            contractInstance = contract;
            this.setState({address: contractInstance.address});
            return;
          });
        })

      }
      render() {
        return (<div className="App">
          {
            this.state.address
              ? <h1>合約地址:{this.state.address}</h1>
              : <div/>
          }
          <h2>上傳圖片到IPFS:</h2>
          /**這一部分用于上傳文件到ipfs**/
          <div>
            <label id="file">Choose file to upload</label>
            <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
          </div>
          <div>
            <button onClick={() => {
                var file = this.refs.file.files[0];
                var reader = new FileReader();
                // reader.readAsDataURL(file);
                reader.readAsArrayBuffer(file)
                reader.onloadend = function(e) {
                  console.log(reader);
                  saveImageOnIpfs(reader).then((hash) => {
                    console.log(hash);
                    this.setState({imgHash: hash})
                  });

                }.bind(this);

              }}>將圖片上傳到IPFS并返回圖片HASH</button>
          </div>
           /**這一部分用于上傳hash到區(qū)塊鏈**/
          {
            this.state.imgHash
              ? <div>
                  <h2>imgHash:{this.state.imgHash}</h2>
                  <button onClick={() => {
                      contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                        console.log('圖片的hash已經(jīng)寫入到區(qū)塊鏈!');
                        this.setState({isWriteSuccess: true});
                      })
                    }}>將圖片hash寫到區(qū)塊鏈:contractInstance.set(imgHash)</button>
                </div>
              : <div/>
          }
          {
            this.state.isWriteSuccess
              ? <div>
                  <h1>圖片的hash已經(jīng)寫入到區(qū)塊鏈!</h1>
                  <button onClick={() => {
                      contractInstance.get({from: account}).then((data) => {
                        console.log(data);
                        this.setState({blockChainHash: data});
                      })
                    }}>從區(qū)塊鏈讀取圖片hash:contractInstance.get()</button>
                </div>
              : <div/>
          }
          {
            this.state.blockChainHash
              ? <div>
                  <h3>從區(qū)塊鏈讀取到的hash值:{this.state.blockChainHash}</h3>
                </div>
              : <div/>
          }
          {
            this.state.blockChainHash
              ? <div>
                  <h2>瀏覽器訪問:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
                  <img alt="" style={{width:200}} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
                </div>
              : <img alt=""/>
          }
        </div>);
      }
    }

    export default App



    該項目算是truffle和ipfs結合以太坊一起使用的綜合案例,用與梳理知識點
    ---------------------
    作者:czZ__czZ
    來源:CSDN
    原文:https://blog.csdn.net/czZ__czZ/article/details/79036567
    版權聲明:本文為博主原創(chuàng)文章,轉載請附上博文鏈接!

    posted on 2019-06-25 08:21 狼愛上貍 閱讀(342) 評論(0)  編輯  收藏 所屬分類: Blockchain

    主站蜘蛛池模板: 国产99在线|亚洲| 亚洲爆乳无码一区二区三区| 在线综合亚洲中文精品| 最近免费最新高清中文字幕韩国| 亚洲AV无码国产精品色午友在线 | 国产精品美女免费视频观看| 四虎影视永久免费观看| 国产精品亚洲五月天高清| 国产不卡免费视频| 亚洲av色香蕉一区二区三区| 国产精品免费视频网站| 精品韩国亚洲av无码不卡区| 免费一级大黄特色大片| 美女扒开屁股让男人桶爽免费| 亚洲AV无码乱码在线观看| 一级毛片**免费看试看20分钟| 久久精品国产亚洲Aⅴ香蕉| 中文字幕无码毛片免费看| 亚洲AV成人无码久久精品老人| 中文字幕在线免费观看| 亚洲人成网站18禁止久久影院 | a毛片在线免费观看| 亚洲精品无码久久久久sm| 99re免费在线视频| 亚洲乱人伦精品图片| 欧洲美熟女乱又伦免费视频| 国产亚洲精品成人久久网站| 久久精品国产亚洲Aⅴ香蕉 | 亚洲人色大成年网站在线观看| 国产成人A在线观看视频免费| 亚洲精品无码久久久久YW| 亚洲成a人片在线播放| 中国极品美軳免费观看| 亚洲网址在线观看| 免费一级特黄特色大片在线 | 亚洲精品中文字幕无乱码麻豆| 国产麻豆剧传媒精品国产免费 | 亚洲一区二区三区高清不卡 | 免费无码又爽又刺激高潮视频| 亚洲小说图片视频| 成人国产mv免费视频|