目录

  • 1. 内容简介
  • 2. IPFS-HTTP效果图
  • 3. 实现步骤
    • 3.1 安装create-react-app
    • 3.2 React项目创建
    • 3.3 运行React项目
    • 3.4 浏览项目
    • 3.5 安装ipfs-api
    • 3.6 完成UI逻辑
    • 3.7 导入IPFS
    • 3.8 编写上传大文本字符串到IPFS的Promise函数
    • 3.9 上传数据到IPFS
    • 3.10 跨域资源共享CORS配置
    • 3.11 再次刷新网页提交数据并在线查看数据
    • 3.12 从IPFS读取数据
    • 3.13 总结
  • 4. 下篇文章预告

1. 内容简介

  • 【IPFS + 区块链 系列】 入门篇 - IPFS环境配置
  • 【IPFS + 区块链 系列】 入门篇 - IPFS+IPNS+个人博客搭建

在前面两篇文章中,第一篇春哥给大家详细介绍了IPFS环境配置,第二篇介绍了IPFS如何搭建个人博客,通过这两篇文章相信大家已经对IPFS有所了解,接下来的这篇文章,我们将为大家讲解js-ipfs-api的简单使用,如何将数据上传到IPFS,以及如何从IPFS通过HASH读取数据。

2. IPFS-HTTP效果图

3. 实现步骤

3.1 安装create-react-app

参考文档:https://reactjs.org/tutorial/tutorial.html

localhost:1123 yuechunli$ npm install -g create-react-app

3.2 React项目创建

localhost:1123 yuechunli$ create-react-app ipfs-http-demo
localhost:ipfs-http-demo yuechunli$ ls
README.md   package.json    src
node_modules    public      yarn.lock
localhost:ipfs-http-demo yuechunli$

3.3 运行React项目

localhost:ipfs-http-demo yuechunli$ npm start
Compiled successfully!You can now view ipfs-http-demo in the browser.Local:            http://localhost:3000/On Your Network:  http://192.168.0.107:3000/Note that the development build is not optimized.
To create a production build, use yarn build.

3.4 浏览项目

浏览器浏览http://localhost:3000

效果如下:

3.5 安装ipfs-api

⚠️:在这里我就不过多的去介绍React的使用以及开发,如果感兴趣的可以去看这套React的视频,学完这套视频你可以直接进企业找React相关的前端开发工作。

  • 项目结构

  • 安装ipfs-api

切换到项目根目录,安装ipfs-api

$ npm uninstall --save ipfs-api
localhost:ipfs-http-demo yuechunli$ ls
README.md   package.json    src
node_modules    public      yarn.lock
localhost:ipfs-http-demo yuechunli$ pwd
/Users/liyuechun/Desktop/1123/ipfs-http-demo
localhost:ipfs-http-demo yuechunli$ npm uninstall --save ipfs-api

⚠️:ipfs安装完后,如上图所示,接下来刷新一下浏览器,看看项目是否有问题,正常来讲,一切会正常,������,Continue,Continue,Continue……

3.6 完成UI逻辑

拷贝下面的代码,将src/App.js里面的代码直接替换掉。

import React, { Component } from 'react';
import './App.css';class App extends Component {constructor(props) {super(props);this.state = {strHash: null,strContent: null}}render() {return (<div className="App"><inputref="ipfsContent"style=/><button onClick={() => {let ipfsContent = this.refs.ipfsContent.value;console.log(ipfsContent);}}>提交到IPFS</button><p>{this.state.strHash}</p><button onClick={() => {console.log('从ipfs读取数据。')}}>读取数据</button><h1>{this.state.strContent}</h1></div>);}
}export default App;

上面的代码完成的工作是,当我们在输入框中输入一个字符串时,点击提交到IPFS按钮,将文本框中的内容取出来打印,后续我们需要将这个数据上传到IPFS。点击读取数据按钮,我们也只是随便打印了一个字符串,后面需要从IPFS读取数据,然后将读取的数据存储到状态机变量strContent中并且展示出来。

3.7 导入IPFS

const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});

3.8 编写上传大文本字符串到IPFS的Promise函数

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);})})}

response[0].hash返回的是数据上传到IPFS后返回的HASH字符串。

3.9 上传数据到IPFS

this.saveTextBlobOnIpfs(ipfsContent).then((hash) => {console.log(hash);this.setState({strHash: hash});
});

ipfsContent是从文本框中取到的数据,调用this.saveTextBlobOnIpfs方法将数据上传后,会返回字符串hash,并且将hash存储到状态机变量strHash中。

目前完整的代码:

import React, {Component} from 'react';
import './App.css';const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});class App extends Component {constructor(props) {super(props);this.state = {strHash: null,strContent: 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"><input ref="ipfsContent" style=/><button onClick={() => {let ipfsContent = this.refs.ipfsContent.value;console.log(ipfsContent);this.saveTextBlobOnIpfs(ipfsContent).then((hash) => {console.log(hash);this.setState({strHash: hash});});}}>提交到IPFS</button><p>{this.state.strHash}</p><button onClick={() => {console.log('从ipfs读取数据。')}}>读取数据</button><h1>{this.state.strContent}</h1></div>);}
}export default App;

测试:

3.10 跨域资源共享CORS配置

跨域资源共享( CORS )配置,依次在终端执行下面的代码:

localhost:ipfs-http-demo yuechunli$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "GET", "POST", "OPTIONS"]'localhost:ipfs-http-demo yuechunli$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'localhost:ipfs-http-demo yuechunli$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials '["true"]'localhost:ipfs-http-demo yuechunli$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Headers '["Authorization"]'localhost:ipfs-http-demo yuechunli$ ipfs config --json API.HTTPHeaders.Access-Control-Expose-Headers '["Location"]'

用正确的端口运行daemon:

localhost:ipfs-http-demo yuechunli$ ipfs config Addresses.API
/ip4/127.0.0.1/tcp/5001
localhost:ipfs-http-demo yuechunli$ ipfs config Addresses.API /ip4/127.0.0.1/tcp/5001
localhost:ipfs-http-demo yuechunli$ ipfs daemon

3.11 再次刷新网页提交数据并在线查看数据

  • 上传数据,并且查看返回hash值

  • 在线查看上传到IPFS的数据

3.12 从IPFS读取数据

  • ipfs.cat
ipfs.cat(this.state.strHash).then((stream) => {console.log(stream);let strContent = Utf8ArrayToStr(stream);console.log(strContent);this.setState({strContent: strContent});
});

streamUint8Array类型的数据,下面的方法是将Uint8Array转换为string字符串。

  • Utf8ArrayToStr
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:// 0xxxxxxxout += String.fromCharCode(c);break;case 12: case 13:// 110x xxxx   10xx xxxxchar2 = array[i++];out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));break;case 14:// 1110 xxxx  10xx xxxx  10xx xxxxchar2 = array[i++];char3 = array[i++];out += String.fromCharCode(((c & 0x0F) << 12) |((char2 & 0x3F) << 6) |((char3 & 0x3F) << 0));break;default:break;}}return out;
}
  • 完整源码
import React, {Component} from 'react';
import './App.css';const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});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:// 0xxxxxxxout += String.fromCharCode(c);break;case 12:case 13:// 110x xxxx   10xx xxxxchar2 = array[i++];out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));break;case 14:// 1110 xxxx  10xx xxxx  10xx xxxxchar2 = 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 = {strHash: null,strContent: 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"><input ref="ipfsContent" style=/><button onClick={() => {let ipfsContent = this.refs.ipfsContent.value;console.log(ipfsContent);this.saveTextBlobOnIpfs(ipfsContent).then((hash) => {console.log(hash);this.setState({strHash: hash});});}}>提交到IPFS</button><p>{this.state.strHash}</p><button onClick={() => {console.log('从ipfs读取数据。')ipfs.cat(this.state.strHash).then((stream) => {console.log(stream);let strContent = Utf8ArrayToStr(stream);console.log(strContent);this.setState({strContent: strContent});});}}>读取数据</button><h1>{this.state.strContent}</h1></div>);}
}export default App;

3.13 总结

这篇文章主要讲解如何配置React环境,如何创建React项目,如何安装js-ipfs-api,如何上传数据,如何设置开发环境,如何下载数据等等内容。通过这篇文章的系统学习,你会掌握js-ipfs-api在项目中的使用流程。

这是【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (上篇)-js-ipfs-api,下篇讲解如何将IPFS和以太坊智能合约结合进行数据存储。

4. 下篇文章预告

这是【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (上篇)-js-ipfs-api,下篇讲解如何将IPFS和以太坊智能合约结合进行数据存储。

http://liyuechun.org/2017/11/22/ipfs-api/

IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (上篇)-js-ipfs-api相关推荐

  1. 【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (下篇)-ipfs + Ethereum 大图片存储

    目录 1. 系列文章 2. 项目描述及效果展示 3. 阅读本文需要掌握的知识 4. 源码 5. 运行程序 6. 技术交流 1. 系列文章 [IPFS + 区块链 系列] 入门篇 - IPFS环境配置 ...

  2. IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (中篇)-js-ipfs-api - 图片上传到IPFS以及下载

    目录 1. 项目效果图 2. 创建React项目 3. 完成UI逻辑 4. 安装ipfs-api 5. App.js导入IPFS 6. 实现上传图片到IPFS的Promise函数 7. 上传图片到IP ...

  3. 【IPFS + 区块链 系列】 入门篇 - IPFS+IPNS+个人博客搭建

    目录 1. 如何在IPFS新增一个文件 1.1 新建file.txt文件 1.2 查看ipfs相关命令 1.3 将file.txt添加到ipfs节点 2. 通过ipfs创建目录存储文件 3. 如何在I ...

  4. ipfs搭建mysql_【IPFS + 区块链 系列】 入门篇 - IPFS环境配置

    孔壹学院:国内区块链职业教育引领品牌. 作者:黎跃春,孔壹学院创始人,区块链.高可用架构师 微信:liyc1215 区块链博客:http://liyuechun.org 目录 1. IPFS简介 IP ...

  5. 【IPFS + 区块链 系列】 入门篇 - IPFS环境配置

    目录 1. IPFS简介 2. IPFS本地环境安装 2.1 下载ipfs压缩包 2.2 安装 3. 项目配置 3.1 创建ipfs节点 3.2 修改节点默认存储空间 3.3 查看节点id 3.4 启 ...

  6. 区块链投资入门篇—骨灰版

    区块链技术未来会大规模地普及,比特币是区块链技术的一种具体应用.能抓住这样的机会是每个人一生中难得的机遇,如同90年代初期的证券市场. 目前很多人普遍的问题是不懂,也懒得看,懒得研究.当你看到这篇教程 ...

  7. 【区块链开发入门】(四) Truffle详解篇2

    由于本篇篇幅较长,因此转为两篇文章.Truffle详解篇篇1请见:link 目录导航页 [区块链开发入门](一) 以太坊的搭建与运行 [区块链开发入门](二) 以太坊的编程接口 [区块链开发入门](三 ...

  8. 【邀请函】Web 3.0中国峰会暨IPFS区块链分布式存储行业大会将于7月15日在成都召开,水滴云邀您一起共话分布式存储未来

    <Web3.0中国峰会暨IPFS区块链分布式存储行业大会>成都站将在7月15-17日成都世纪城新国际会展中心举办,共享分布式存储新机遇!行业盛会,巅峰相聚,助力国家"东数西算&q ...

  9. 《Web3.0中国峰会暨IPFS区块链分布式存储行业大会》开启

    <Web3.0中国PFS区块链分布式存储>开启 Web3.0中国峰会暨IPFS区块链分布式存储行业大会>于7月15日在中国成都,盛大开启!共享分布式存储新机遇,行业盛会,巅峰相聚,助 ...

最新文章

  1. 为asa防火墙配置ssh登陆
  2. Linux防火墙详解(二)
  3. hdu 3183 A Magic Lamp(给一个n位的数,从中删去m个数字,使得剩下的数字组成的数最小(顺序不能变),然后输出)...
  4. SAP 电商云 Spartacus UI Quick Order 主页的实现
  5. 使用ABAP Push Channel(APC)开发的乒乓球游戏,可双打
  6. vue require css html,requirejs vue vue.router简单框架
  7. (二)Cypher语言常用方法举例
  8. Mac 如何寻找Mac自带的IDLE
  9. 推特超2K赞,DeepMind强化学习综述:她可以很快,但快从慢中来
  10. VS2010对C++11的语法支持简单示例
  11. CC3200在sl_Start函数处不断重启复位的原因解析
  12. 机器学习基础(十八) —— decision stump
  13. Asp.net Ajax Control Toolkit设计编程备忘录(色眼窥观版)——第3回(UE专辑)
  14. struts2在action中获取request、session、application,并传递数据
  15. python第二天3.1
  16. iPhone Web App及优缺点【书摘】
  17. linux下查看so文件内容,linux查看so文件的一些信息命令
  18. 爬取东方财富的利润表数据记录
  19. number of splits 划分的条件
  20. 解析函数论 Page 22 达朗贝尔判别法 VS 柯西判别法

热门文章

  1. 2015年10月5日 正式启用该博客
  2. Android:阻止输入法将图片压缩变形
  3. 草根版创业网站学巴菲特售时间 获天使投资
  4. 如何利用ESP8266模块实现远程控制
  5. 吴恩达 coursera AI 专项二第三课总结+作业答案
  6. 现代谱估计:MTM 谐波分析
  7. 【转】IAR与Keil两款开发工具区别
  8. 断言(assert)详解
  9. 科大星云诗社动态20210504
  10. 云炬随笔20171205