【IPFS 區塊鏈 系列】 入門篇 – IPFS Ethereum (下篇)-ipfs Ethereum 大圖片儲存

NO IMAGE

區塊鏈技術部落格:http://liyuechun.org
區塊鏈視訊網站:http://www.kongyixueyuan.com

Ebay專案

基於以太坊Ethereum & IPFS的去中心化Ebay區塊鏈專案詳情連結

目錄

1. 系列文章

2. 專案描述及效果展示

這篇文章通過truffle unbox react建立專案,安裝ipfs-api,將圖片儲存到ipfs,將圖片hash儲存到Ethereum區塊鏈,取資料時先從區塊鏈讀取圖片hash,再通過hashipfs讀取資料,解決了區塊鏈大資料儲存成本高昂的問題。


3. 閱讀本文需要掌握的知識

閱讀本文需要將先學習上面的系列文章,由於本文前端使用了大量的React語法,所以建議學習一些React語法,還需要學習truffle framework

4. 原始碼

其實這篇文章的內容就是上面幾篇文章的綜合結合體,所以在這裡我將不再對程式碼做過多的概述。

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;
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);
}
});
getWeb3.then(results => {
this.setState({web3: results.web3})
// Instantiate contract once web3 provided.
this.instantiateContract()
}).catch(() => {
console.log('Error finding web3.')
})
}
instantiateContract = () => {
simpleStorage.setProvider(this.state.web3.currentProvider);
this.state.web3.eth.getAccounts((error, accounts) => {
account = accounts[0];
simpleStorage.at('0x66e9bbfe244799149a9c4eb708a34ea7c9ce67e2').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>
<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>
{
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: 1600
}} src={"http://localhost:8080/ipfs/"   this.state.imgHash}/>
</div>
: <img alt=""/>
}
</div>);
}
}
export default App

5. 執行程式

  • 專案下載
$ git clone https://github.com/liyuechun/IPFS-Ethereum-Image.git
$ cd IPFS-Ethereum-Image
$ npm install
  • 執行程式
$ ipfs daemon // 終端一
$ npm start   // 終端二

6. 技術交流

  • 區塊鏈技術交流QQ群:348924182
  • 進微信群請加微信:liyc1215
  • 「區塊鏈部落」官方公眾號