# Dapp-IPFS-Image
基于IPFS去中心化相册以太坊Dapp
>注意: 使用该 github 克隆到本地, 需要 执行 `$ npm install` 安装依赖 node_modules
## 安装IPFS
官网(访问不了时,需要科学上网) [https://ipfs.io](https://ipfs.io)
下载
解压缩
`$ tar xvfz go-ipfs_v0.4.10_darwin-amd64.tar.gz`
`$ cd go-ipfs`
`$ mv ipfs /usr/local/bin/ipfs`
### 创建IPFS节点
`$ ipfs init`
`$ cd ~/.ipfs`
### 启动服务器
`ipfs daemon`
### 跨域资源共享 CORS配置
`control + c` 终止ipfs服务器进程
```
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "GET", "POST", "OPTIONS"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials '["true"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Headers '["Authorization"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Expose-Headers '["Location"]'
```
### 验证
启动IPFS服务器
`$ ipfs daemon`
**新建**终端执行:
`$ ipfs cat /ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme`
打开[http://localhost:5001/webui](http://localhost:5001/webui)会看到UI界面
> 需要 truffle ,node.js ,npm ,react 环境安装 参考之前环境配置文章
## 项目开发
新建项目文件夹
`$ mkdir 项目名IPFS-Image`
`cd IPFS-Image`
下载unbox react 框架
`$ truffle unbox react`
### 安装ipfs-api
`$ npm install ipfs-api --save-dev`
### 验证框架和环境:
编译合约
`$ truffle compile`
开启前端
`$ npm start`
看见 项目页面, ok
### 修改项目框架代码:
Atom编辑器打开项目:
`$ atom ./`
### 编写智能合约
修改`contracts/SimpleStorage.sol`文件
```solidity
pragma solidity ^0.4.19;
contract SimpleStorage {
string[] public photoArr; //定义一个 装图片hash值的字符串数组
function storePhoto(string hash) public { //定义添加新图片hash方法
photoArr.push(hash); //往字符串数组末尾 添加 新图片的 hash
}
function getPhoto(uint index) public view returns (uint, string){ //定义函数:传入图片序列号,获取图片hash数组长度 和 对应序列号的 装图片hash值的字符串数组
return (photoArr.length, photoArr[index]);
}
}
```
### 修改 src/app.js
```javascript
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'
import ipfsAPI from 'ipfs-api'
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocal: 'http'})
const contractAddress = "0xd7d25cd0f1ab028a43576b93380c52992716a0d1"
let simpleStorageInstance
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 = {
photos: [],
count: 0,
web3: null
}
}
componentWillMount() {
// Get network provider and web3 instance. See utils/getWeb3 for more info.
getWeb3.then(results => {
this.setState({web3: results.web3})
this.instantiateContract()
}).catch(() => {
console.log('Error finding web3.')
})
}
instantiateContract() {
const that = this
const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
simpleStorage.setProvider(this.state.web3.currentProvider)
this.state.web3.eth.getAccounts((error, accounts) => {
simpleStorage.at(contractAddress).then((instance) => {
simpleStorageInstance = instance
})
.then(result => {
return simpleStorageInstance.getPhoto(0)
})
.then(result => {
console.log(result)
let imgNum = result[0].c[0]
if(imgNum===0){
return
}
if(imgNum===1){
this.setState({
count: imgNum,
photos: this.state.photos.concat([result[1]])
})
}
if(imgNum>1){
for(let i=0;i<imgNum;i++){
(function(i){
simpleStorageInstance.getPhoto(i)
.then(result => {
that.setState({
photos: that.state.photos.concat([result[1]])
})
})
})(i)
}
}
})
})
}
render() {
let doms = [],
photos = this.state.photos
for(let i=0; i<photos.length;i++){
doms.push(<div key={i}><img src={"http://localhost:8080/ipfs/" + photos[i]}/></div>)
}
return (
<div className="App">
<header>上传图片至ipfs,并保存信息至以太坊区块</header>
<div className="upload-container">
<label id="file">选择图片</label>
<input type="file" ref="file" id="file" name="file" multiple="multiple" onChange={e => this.change(e)}/>
<button onClick={() => this.upload()}>上传</button>
</div>
<div className="img-container">
{doms}
</div>
</div>
);
}
upload() {
var file = this.refs.file.files[0];
console.log(file)
var reader = new FileReader();
// reader.readAsDataURL(file);
reader.readAsArrayBuffer(file)
reader.onloadend = (e) => {
//console.log(reader);
saveImageOnIpfs(reader).then((hash) => {
console.log(hash);
this.setState({imgSrc: hash})
simpleStorageInstance.storePhoto(hash, {from: this.state.web3.eth.accounts[0]})
.then(() => {
console.log("写入区块成功")
this.setState({
photos: this.state.photos.concat([hash])
})
})
});
}
}
change(e){
console.log(e.target.value)
}
}
export default App
```
### 修改src/app.css 前端 UI CSS
```css
/* PAGE */
* {
margin: 0;
padding: 0;
}
html, body, #root, .App{
width: 100%;
height: 100%;
}
.App{
display: flex;
flex-direction: column;
}
header{
height: 60px;
line-height: 60px;
padding: 0 20px;
background: #cfd8dc;
border-bottom: 1px solid #eee;
font-size: 24px;
color: #fff;
}
.upload-container {
height: 100px;
display: flex;
justify-content: center;
align-items: center;
background: #cfd8dc;
color: #666;
}
.img-container {
flex: 1;
display: flex;
flex-wrap: wrap;
justify-content: center;
/* align-items: center; */
height: 80px;
background: #eceff1;
}
.img-container div{
width: 200px;
height: 200px;
margin: 20px;
box-shadow: 0 0 10px #ccc;
border-radius: 3px;
}
.img-container div{
display: flex;
justify-content: center;
align-items: center;
}
.img-container div img{
max-width: 200px;
max-height: 200px;
}
.upload-container input{
font-size: 14px;
display: flex;
align-items: center;
margin-left: 10px;
}
.upload-container button{
height: 30px;
width: 80px;
line-height: 30px;
font-size: 14px;
color: #fff;
border: 0;
outline: none;
cursor: pointer;
border-radius: 3px;
background: cadetblue
}
.upload-container button:hover{
opacity: 0.7;
}
```
### 本地测试:
> 编译部署合约
`$ truffle develop //启动truffle本地合约测试框架`
![](http://p37d7w3w4.bkt.clouddn.com/truffledevelop.png)
(Mnemonic:后面 就是本地 以太坊测试框架区块链 钱包的助记词,可用于直接导入 Metamask钱包中)
`$ truffle(develop)> compile //编译`
`$ truffle(develop)> migrate //部署合约`
![](http://p37d7w3w4.bkt.clouddn.com/migrate.png)
>复制智能合约 SimpleStorage 的地址
- 修改 `src/app.js` 合约地址
`const contractAddress = "0x345ca3e014aaf5dca488057592ee47305d9b3e10" //SimpleStorage合约地址`
![](http://p37d7w3w4.bkt.clouddn.com/%E6%94%B9%E5%90%88%E7%BA%A6.png)
- **新建**终端(truffle develop框架不要关), 启动IPFS服务
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
【资源概览】 区块链 基于IPFS去中心化相册以太坊Dapp源码+项目资料齐全+部署文档 高分项目.zip区块链 基于IPFS去中心化相册以太坊Dapp源码+项目资料齐全+部署文档 高分项目.zip区块链 基于IPFS去中心化相册以太坊Dapp源码+项目资料齐全+部署文档 高分项目.zip 【资源说明】 高分项目源码:此资源是在校高分项目的完整源代码,经过导师的悉心指导与认可,答辩评审得分高达95分,项目的质量与深度有保障。 测试运行成功:所有的项目代码在上传前都经过了严格的测试,确保在功能上完全符合预期,您可以放心下载并使用。 适用人群广泛:该项目不仅适合计算机相关专业(如软件工程、计科、区块链、人工智能、电子信息、物联网、通信工程、自动化等)的在校学生和老师,还可以作为毕业设计、课程设计、作业或项目初期立项的演示材料。对于希望进阶学习的小白来说,同样是一个极佳的学习资源。 代码灵活性高:如果您具备一定的编程基础,可以在此代码基础上进行个性化的修改,以实现更多功能。当然,直接用于毕业设计、课程设计或作业也是完全可行的。 欢迎下载,与我一起交流学习,共同进步!
资源推荐
资源详情
资源评论
收起资源包目录
区块链 基于IPFS去中心化相册以太坊Dapp源码+项目资料齐全+部署文档 高分项目.zip (55个子文件)
教程文档.md 4KB
Dapp-IPFS-Image-master
box-img-lg.png 111KB
truffle-config.js 135B
migrations
2_deploy_contracts.js 138B
1_initial_migration.js 129B
src
App.test.js 202B
utils
getWeb3.js 1002B
App.js 3KB
App.css 1KB
css
pure-min.css 16KB
oswald.css 1KB
open-sans.css 642B
index.js 149B
index.css 63B
fonts
Oswald-300
Oswald-300.woff2 10KB
Oswald-300.eot 16KB
LICENSE.txt 4KB
Oswald-300.svg 55KB
Oswald-300.ttf 30KB
Oswald-300.woff 13KB
Oswald-regular
Oswald-regular.woff 12KB
LICENSE.txt 4KB
Oswald-regular.svg 55KB
Oswald-regular.ttf 34KB
Oswald-regular.woff2 10KB
Oswald-regular.eot 18KB
Open-Sans-regular
Open-Sans-regular.ttf 33KB
Open-Sans-regular.svg 105KB
LICENSE.txt 11KB
Open-Sans-regular.eot 18KB
Open-Sans-regular.woff2 10KB
Open-Sans-regular.woff 14KB
LICENSE 1KB
box-img-sm.png 5KB
package.json 3KB
public
favicon.ico 31KB
index.html 1KB
package-lock.json 401KB
test
simplestorage.js 524B
TestSimpleStorage.sol 434B
truffle.js 154B
contracts
SimpleStorage.sol 564B
Migrations.sol 514B
README.md 9KB
config
jest
cssTransform.js 323B
fileTransform.js 301B
polyfills.js 613B
webpack.config.dev.js 9KB
paths.js 2KB
webpack.config.prod.js 10KB
env.js 1KB
scripts
build.js 8KB
test.js 994B
start.js 12KB
171265889347208773632.zip 416B
共 55 条
- 1
资源评论
IT狂飙
- 粉丝: 4776
- 资源: 2641
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功