狼爱上狸

我胡汉三又回来了

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结合以太坊一起使用的综合案例,用与梳理知识点
---------------------
作者:czZ__czZ
来源:CSDN
原文:https://blog.csdn.net/czZ__czZ/article/details/79036567
版权声明:本文为博主原创文章,转载请附上博文链接!

posted on 2019-06-25 08:21 狼爱上狸 阅读(332) 评论(0)  编辑  收藏 所属分类: Blockchain


只有注册用户登录后才能发表评论。


网站导航: