安装create-react-app
npm install -g create-react-php
react项目创建
create-react-app ipfs-http-demo
启动项目
npm start
输入 127.0.0.1:3000
重启一个cmd 安装ipfs-api
npm install --save-dev ipfs-api
终端输入
ipfs confis Addresses。API
App.js
import React, { Component } from 'react';
import './App.css';
//导入ipfs-API
var ipfsAPI =require('ipfs-api')
//获得ipfs的对象
var ipfs = ipfsAPI({host:'localhost',port:'5001',protocol:'http'})
//把utf8字符转换
function Utf8ArrayTostr(array){
var out,i,len,c;
var char2,char3;
out = "";
len = array.length;
i = 0;
while(i<len){
c = array[i++];
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
out += String.fromCharCode(c);
break;
case 12:
case 13:
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6 ) | (char2 & 0x3F));
break;
case 14:
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |((char2 & 0x3F) << 6) |((char3 & 0x3F) << 0));
break;
default:
break;
}
}
return out;
}
class App extends Component {
//创建构造函数
constructor(props){
super(props);
this.state={
hash:null,
content:null
}
}
//文件上传
saveTextBlobOnIpfs = (blob) =>{
return new Promise(function(resolve,reject){
const descBuffer = Buffer.from(blob,'utf-8');
ipfs.add(descBuffer).then((response)=>{
console.log(response)
resolve(response[0].hash);
}).catch((err)=>{
console.error(err)
reject(err);
})
})
}
render() {
return (
<div className="App">
<h1>十二</h1>
<input
ref="ipfs"
style={{width:200,height:50}}/>
<button
onClick={() =>{
let content = this.refs.ipfs.value;
console.log(content)
this.saveTextBlobOnIpfs(content).then((hash)=>{
console.log("内容的hash:"+hash);
this.setState({hash});
})
}}
style={{heigth:50}}>将数据提交到IPFS</button>
{
//判断他是否为空不为空显示
this.state.hash ? <h1>{this.state.hash}</h1>:""
}
<button onClick={()=>{
ipfs.cat(this.state.hash).then((stream) =>{
console.log(stream);
let content = Utf8ArrayTostr(stream);
console.log(content);
this.setState({content});
});
}}>从IPFS读取数据</button>
{this.state.content ? <h1>{this.state.content}</h1> : ""
}
</div>
);
}
}
export default App;
ipfs config Addresses.API /ip4/127.0.0.1/tcp/5001