【区块链 | IPFS】React通过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 {undefined
  constructor(props){undefined
      super(props);
      this.state={undefined
        hash:null,
        content:null
      }
  }

  saveTextOnIpfs=(blob)=>{undefined

  return new Promise(function(reslove,reject){undefined

  const docBuffer=Buffer.from(blob,'utf-8');
  ipfs.add(docBuffer).then((response)=>{undefined

        console.log(response);
        reslove(response[0].hash)
      }).catch((err)=>{undefined
        console.error(err);
        reject(err);
      })

    })
  }

11. 在App.js中增加按钮和输入框及事件触发

<input
           ref="ipfscontent"
           style={undefined{width:200,height:50}}/>
          <button
           onClick={()=>{undefined
              console.log("I am submiting...");
              let content = this.refs.ipfscontent.value;
              console.log(content);


              this.saveTextOnIpfs(content).then((hash)=>{undefined


                console.log("hash"+hash);


                this.setState({hash:hash});


              })
           }}
           style={undefined{height:50}}>Submit To Ipfs</button>

          <button  onClick={()=>{undefined
              ipfs.cat(this.state.hash).then((stream)=>{undefined

                  console.log(stream);
                  var content=stream;
                  this.setState({content});
              });

          }}
          >Get From IPFS</button>
           {undefined
              this.state.hash ? <h1>{this.state.hash}</h1>:""
           }
          {undefined
            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码,通过函数转化即可

猜你喜欢

转载自blog.csdn.net/qq_28505809/article/details/123947219