4.通过ipfs-api上传文件到ipfs
本节主要讨论如何基于Web前端调用ipfs-api上传文件到ipfs,通过npm start 启动项目
1. 安装create-react-app
通过npm install 安装 create-react-app,便于后续创建项目
npm install -g create create-react-app
2. 创建项目
通过 create-react-app myipfs 来创建项目
3. 查看目录结构
通过atom打开项目
4. 启动服务器
通过 npm start 启动服务器,出现下面的界面代表服务器启动成功
5.查看页面
服务器启动成功后,会自动弹出以下界面
6. 安装 ipfs-api组件
7. 设置端口
# Show the ipfs config API port to check it is correct > ipfs config Addresses.API /ip4/127.0.0.1/tcp/5001 # Set it if it does not match the above output > ipfs config Addresses.API /ip4/127.0.0.1/tcp/5001 # Restart the daemon after changing the config # Run the daemon > ipfs daemon
8.在App.js中注册ipfs
在github中搜索 ipfs js 可以找到相应的信息,注意选择最后一个“ipfs/js-ipfs-api”
从中可以找到以下内容完成ipfs-api的注册,注意这里选择第一个和最后一个即可
9. CORS配置
ipfs需要进行跨域配置,否则会出现以下错误
10. 在App.js中增加函数
var ipfsAPI = require('ipfs-api')
var ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'})
class App extends Component {
constructor(props){
super(props);
this.state={
hash:null,
content:null
}
}
saveTextOnIpfs=(blob)=>{
return new Promise(function(reslove,reject){
const docBuffer=Buffer.from(blob,'utf-8');ipfs.add(docBuffer).then((response)=>{
console.log(response);
reslove(response[0].hash)
}).catch((err)=>{
console.error(err);
reject(err);
})
})
}
11. 在App.js中增加按钮和输入框及事件触发
<input
ref="ipfscontent"
style={{width:200,height:50}}/>
<button
onClick={()=>{
console.log("I am submiting...");
let content = this.refs.ipfscontent.value;
console.log(content);
this.saveTextOnIpfs(content).then((hash)=>{
console.log("hash"+hash);
this.setState({hash:hash});
})
}}
style={{height:50}}>Submit To Ipfs</button>
<button onClick={()=>{
ipfs.cat(this.state.hash).then((stream)=>{
console.log(stream);
var content=stream;
this.setState({content});
});
}}
>Get From IPFS</button>
{
this.state.hash ? <h1>{this.state.hash}</h1>:""
}
{
this.state.content ? <h1>{this.state.content}</h1> : ""
}
界面显示效果如下
12. 提交内容到IPFS
当点击“Submit To Ipfs”按钮会触发saveTextOnIpfs,将输入的内容保存到ipfs
比如输入 abc,点击“Submit To Ipfs”按钮,出现以下界面
其中 QmQpeUrxt....是ipfs返回的输入内容的hash值
13. 从ipfs返回数据
点击“Get From IPFS”,会出现以下内容,其中979899是abc返回的ascii码,通过函数转化即可
作者:温春水 致力于研究区块链技术
微信:wencs1314 QQ群:612968783