ipfs + 以太坊實例解析

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

我個人只是作爲記錄學習心得所借鑑

項目流程

首先調用代碼創建truffle項目

truffle unbox react

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

npm install –save ipfs-api

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

compile

替換合約地址,這個需要將合約在以太坊部署並取得對應地址
然後運行ipfs節點

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);
    })
  })
}

//創建構造函數,添加狀態機變量//

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

    this.state = {
      blockChainHash: null,
      web3: null,
      address: null,
      imgHash: null,
      isWriteSuccess: false
    }
  }
//程序啓動默認調用方法//
  componentWillMount() {
    //打印項目中網絡節點//
    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到區塊鏈**/
      {
        this.state.imgHash
          ? <div>
              <h2>imgHash:{this.state.imgHash}</h2>
              <button onClick={() => {
                  contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                    console.log('圖片的hash已經寫入到區塊鏈!');
                    this.setState({isWriteSuccess: true});
                  })
                }}>將圖片hash寫到區塊鏈:contractInstance.set(imgHash)</button>
            </div>
          : <div/>
      }
      {
        this.state.isWriteSuccess
          ? <div>
              <h1>圖片的hash已經寫入到區塊鏈!</h1>
              <button onClick={() => {
                  contractInstance.get({from: account}).then((data) => {
                    console.log(data);
                    this.setState({blockChainHash: data});
                  })
                }}>從區塊鏈讀取圖片hash:contractInstance.get()</button>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h3>從區塊鏈讀取到的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結合以太坊一起使用的綜合案例,用與梳理知識點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章