{"id":14956280,"url":"https://github.com/liyuechun/ipfs-ethereum-image","last_synced_at":"2025-10-01T17:31:18.488Z","repository":{"id":37735697,"uuid":"112067628","full_name":"liyuechun/IPFS-Ethereum-Image","owner":"liyuechun","description":"【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum （下篇）-ipfs + Ethereum 大图片存储","archived":false,"fork":false,"pushed_at":"2017-11-26T08:46:15.000Z","size":487,"stargazers_count":62,"open_issues_count":0,"forks_count":35,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-01-14T12:00:07.214Z","etag":null,"topics":["ethereum","ipfs","ipfs-api","ipfs-blockchain","ipfs-ethereum","ipfs-hash"],"latest_commit_sha":null,"homepage":"http://liyuechun.org","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/liyuechun.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-11-26T08:33:54.000Z","updated_at":"2024-06-09T08:51:06.000Z","dependencies_parsed_at":"2022-09-01T08:21:12.776Z","dependency_job_id":null,"html_url":"https://github.com/liyuechun/IPFS-Ethereum-Image","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liyuechun%2FIPFS-Ethereum-Image","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liyuechun%2FIPFS-Ethereum-Image/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liyuechun%2FIPFS-Ethereum-Image/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liyuechun%2FIPFS-Ethereum-Image/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/liyuechun","download_url":"https://codeload.github.com/liyuechun/IPFS-Ethereum-Image/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234883233,"owners_count":18901366,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ethereum","ipfs","ipfs-api","ipfs-blockchain","ipfs-ethereum","ipfs-hash"],"created_at":"2024-09-24T13:12:38.515Z","updated_at":"2025-10-01T17:31:13.134Z","avatar_url":"https://github.com/liyuechun.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum （下篇）-ipfs + Ethereum 大图片存储\n\n\u003e [区块链技术博客：http://liyuechun.org](http://liyuechun.org)\n\u003e [区块链视频网站：http://www.kongyixueyuan.com](http://www.kongyixueyuan.com)\n\n\n## Ebay项目\n\n**基于以太坊Ethereum \u0026 IPFS的去中心化Ebay区块链项目[详情链接](https://mp.weixin.qq.com/s/feY21MxV_-LuWogPW6qqWA)**\n\n![](http://om1c35wrq.bkt.clouddn.com/ipfs-http.png)\n\n## 目录\n\n- [1. 系列文章](#1-系列文章)\n- [2. 项目描述及效果展示](#2-项目描述及效果展示)\n- [3. 阅读本文需要掌握的知识](#3-阅读本文需要掌握的知识)\n- [4. 源码](#4-源码)\n- [5. 运行程序](#5-运行程序)\n- [6. 技术交流](#6-技术交流)\n\n\n## 1. 系列文章\n\n- [【IPFS + 区块链 系列】 入门篇 - IPFS环境配置](http://liyuechun.org/2017/11/20/ipfs-blockchain/)\n- [【IPFS + 区块链 系列】 入门篇 - IPFS+IPNS+个人博客搭建](http://liyuechun.org/2017/11/21/ipfs-blockchain-blogger/)\n- [【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum （上篇）-js-ipfs-api - 数据上传到IPFS](http://liyuechun.org/2017/11/22/ipfs-api/)\n- [【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum （中篇）-js-ipfs-api - 图片上传到IPFS以及下载](http://liyuechun.org/2017/11/26/ipfs-upload-image/)\n\n## 2. 项目描述及效果展示\n\n这篇文章通过`truffle unbox react`创建项目，安装`ipfs-api`，将图片存储到`ipfs`，将图片`hash`存储到`Ethereum`区块链，取数据时先从区块链读取图片`hash`，再通过`hash`从`ipfs`读取数据，解决了区块链大数据存储成本高昂的问题。\n\n![](http://om1c35wrq.bkt.clouddn.com/ipfs-ether-image-0001gif.gif)\n![](http://om1c35wrq.bkt.clouddn.com/ipfs-ether-image--0002.gif)\n\n\n## 3. 阅读本文需要掌握的知识\n\n阅读本文需要将先学习上面的系列文章，由于本文前端使用了大量的React语法，所以建议学习一些[React语法](http://edu.csdn.net/course/play/4749)，还需要学习[truffle framework](http://truffleframework.com/)。\n\n## 4. 源码\n\n其实这篇文章的内容就是上面几篇文章的综合结合体，所以在这里我将不再对代码做过多的概述。\n\n```\nimport React, {Component} from 'react'\nimport SimpleStorageContract from '../build/contracts/SimpleStorage.json'\nimport getWeb3 from './utils/getWeb3'\n\nimport './css/oswald.css'\nimport './css/open-sans.css'\nimport './css/pure-min.css'\nimport './App.css'\n\nconst ipfsAPI = require('ipfs-api');\nconst ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});\n\nconst contract = require('truffle-contract')\nconst simpleStorage = contract(SimpleStorageContract)\nlet account;\n\n// Declaring this for later so we can chain functions on SimpleStorage.\nlet contractInstance;\n\nlet saveImageOnIpfs = (reader) =\u003e {\n  return new Promise(function(resolve, reject) {\n    const buffer = Buffer.from(reader.result);\n    ipfs.add(buffer).then((response) =\u003e {\n      console.log(response)\n      resolve(response[0].hash);\n    }).catch((err) =\u003e {\n      console.error(err)\n      reject(err);\n    })\n  })\n}\n\nclass App extends Component {\n  constructor(props) {\n    super(props)\n\n    this.state = {\n      blockChainHash: null,\n      web3: null,\n      address: null,\n      imgHash: null,\n      isWriteSuccess: false\n    }\n  }\n\n  componentWillMount() {\n\n    ipfs.swarm.peers(function(err, res) {\n      if (err) {\n        console.error(err);\n      } else {\n        // var numPeers = res.Peers === null ? 0 : res.Peers.length;\n        // console.log(\"IPFS - connected to \" + numPeers + \" peers\");\n        console.log(res);\n      }\n    });\n\n    getWeb3.then(results =\u003e {\n      this.setState({web3: results.web3})\n\n      // Instantiate contract once web3 provided.\n      this.instantiateContract()\n    }).catch(() =\u003e {\n      console.log('Error finding web3.')\n    })\n  }\n\n  instantiateContract = () =\u003e {\n\n    simpleStorage.setProvider(this.state.web3.currentProvider);\n    this.state.web3.eth.getAccounts((error, accounts) =\u003e {\n      account = accounts[0];\n      simpleStorage.at('0x66e9bbfe244799149a9c4eb708a34ea7c9ce67e2').then((contract) =\u003e {\n        console.log(contract.address);\n        contractInstance = contract;\n        this.setState({address: contractInstance.address});\n        return;\n      });\n    })\n\n  }\n  render() {\n    return (\u003cdiv className=\"App\"\u003e\n      {\n        this.state.address\n          ? \u003ch1\u003e合约地址：{this.state.address}\u003c/h1\u003e\n          : \u003cdiv/\u003e\n      }\n      \u003ch2\u003e上传图片到IPFS：\u003c/h2\u003e\n      \u003cdiv\u003e\n        \u003clabel id=\"file\"\u003eChoose file to upload\u003c/label\u003e\n        \u003cinput type=\"file\" ref=\"file\" id=\"file\" name=\"file\" multiple=\"multiple\"/\u003e\n      \u003c/div\u003e\n      \u003cdiv\u003e\n        \u003cbutton onClick={() =\u003e {\n            var file = this.refs.file.files[0];\n            var reader = new FileReader();\n            // reader.readAsDataURL(file);\n            reader.readAsArrayBuffer(file)\n            reader.onloadend = function(e) {\n              console.log(reader);\n              saveImageOnIpfs(reader).then((hash) =\u003e {\n                console.log(hash);\n                this.setState({imgHash: hash})\n              });\n\n            }.bind(this);\n\n          }}\u003e将图片上传到IPFS并返回图片HASH\u003c/button\u003e\n      \u003c/div\u003e\n      {\n        this.state.imgHash\n          ? \u003cdiv\u003e\n              \u003ch2\u003eimgHash：{this.state.imgHash}\u003c/h2\u003e\n              \u003cbutton onClick={() =\u003e {\n                  contractInstance.set(this.state.imgHash, {from: account}).then(() =\u003e {\n                    console.log('图片的hash已经写入到区块链！');\n                    this.setState({isWriteSuccess: true});\n                  })\n                }}\u003e将图片hash写到区块链：contractInstance.set(imgHash)\u003c/button\u003e\n            \u003c/div\u003e\n          : \u003cdiv/\u003e\n      }\n      {\n        this.state.isWriteSuccess\n          ? \u003cdiv\u003e\n              \u003ch1\u003e图片的hash已经写入到区块链！\u003c/h1\u003e\n              \u003cbutton onClick={() =\u003e {\n                  contractInstance.get({from: account}).then((data) =\u003e {\n                    console.log(data);\n                    this.setState({blockChainHash: data});\n                  })\n                }}\u003e从区块链读取图片hash：contractInstance.get()\u003c/button\u003e\n            \u003c/div\u003e\n          : \u003cdiv/\u003e\n      }\n      {\n        this.state.blockChainHash\n          ? \u003cdiv\u003e\n              \u003ch3\u003e从区块链读取到的hash值：{this.state.blockChainHash}\u003c/h3\u003e\n            \u003c/div\u003e\n          : \u003cdiv/\u003e\n      }\n      {\n        this.state.blockChainHash\n          ? \u003cdiv\u003e\n              \u003ch2\u003e浏览器访问：{\"http://localhost:8080/ipfs/\" + this.state.imgHash}\u003c/h2\u003e\n              \u003cimg alt=\"\" style={{\n                  width: 1600\n                }} src={\"http://localhost:8080/ipfs/\" + this.state.imgHash}/\u003e\n            \u003c/div\u003e\n          : \u003cimg alt=\"\"/\u003e\n      }\n    \u003c/div\u003e);\n  }\n}\n\nexport default App\n```\n\n\n## 5. 运行程序\n\n- 项目下载\n\n```\n$ git clone https://github.com/liyuechun/IPFS-Ethereum-Image.git\n$ cd IPFS-Ethereum-Image\n$ npm install\n```\n\n- 运行程序\n\n```\n$ ipfs daemon // 终端一\n$ npm start   // 终端二\n```\n\n## 6. 技术交流\n\n- 区块链技术交流QQ群：`348924182`\n- 进微信群请加微信：`liyc1215`\n- 「区块链部落」官方公众号\n\n![](http://om1c35wrq.bkt.clouddn.com/%E5%8C%BA%E5%9D%97%E9%93%BE%E9%83%A8%E8%90%BD.png)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliyuechun%2Fipfs-ethereum-image","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fliyuechun%2Fipfs-ethereum-image","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliyuechun%2Fipfs-ethereum-image/lists"}