【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (中篇)-js-ipfs-api - IPFS图片上传与下载

Ebay项目

基于以太坊Ethereum & IPFS的去中心化Ebay区块链项目详情链接

目录

系列文章

1. 项目效果图

选择图片,点击Submit将图片提交到IPFS,并且返回IPFSHASH值,再通过HASHIPFS读取图片。

上传图片到IPFS

2. 创建React项目

具体不知道怎么操作的,请移步到【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (上篇)-js-ipfs-api

$ create-react-app ipfs_img

3. 完成UI逻辑

将下面的代码拷贝替换掉App.js里面的代码。

import React, {Component} from 'react'

class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      imgSrc: null
    }
  }


  render() {
    return (<div className="App">

      <h2>上传图片到IPFS:</h2>
      <div>
        <label id="file">Choose file to upload</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = (e) => {
              console.log(reader);
              // 上传数据到IPFS
            }

          }}>Submit</button>
      </div>
      {
        this.state.imgSrc
          ? <div>
              <h2>{"http://localhost:8080/ipfs/" + this.state.imgSrc}</h2>
              <img alt="区块链部落" style={{
                  width: 1600
                }} src={"http://localhost:8080/ipfs/" + this.state.imgSrc}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}

export default App

IPFS UI逻辑

4. 安装ipfs-api

localhost:1126 yuechunli$ cd ipfs_img/
localhost:ipfs_img yuechunli$ ls
README.md   package.json    src
node_modules    public      yarn.lock
localhost:ipfs_img yuechunli$ npm install --save-dev ipfs-api

5. App.js导入IPFS

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

6. 实现上传图片到IPFS的Promise函数

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

7. 上传图片到IPFS

var file = this.refs.file.files[0];
var reader = new FileReader();
// reader.readAsDataURL(file);
reader.readAsArrayBuffer(file)
reader.onloadend = function(e) {
  console.log(reader);
  saveImageOnIpfs(reader).then((hash) => {
    console.log(hash);
    this.setState({imgSrc: hash})
  });
  • reader.readAsDataURL(file);上传图片路径。
  • reader.readAsArrayBuffer(file)上传图片内容
  • 上传图片
saveImageOnIpfs(reader).then((hash) => {
    console.log(hash);
    this.setState({imgSrc: hash})
  });

hash即是上传到IPFS的图片的HASH地址,this.setState({imgSrc: hash})hash保存到状态机变量imgSrc中。

8. 完整代码

import React, {Component} from 'react'

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

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 = {
      imgSrc: null
    }
  }

  render() {
    return (<div className="App">

      <h2>上传图片到IPFS:</h2>
      <div>
        <label id="file">Choose file to upload</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = (e) => {
              console.log(reader);
              // 上传数据到IPFS
              saveImageOnIpfs(reader).then((hash) => {
                console.log(hash);
                this.setState({imgSrc: hash})
              });
            }

          }}>Submit</button>
      </div>
      {
        this.state.imgSrc
          ? <div>
              <h2>{"http://localhost:8080/ipfs/" + this.state.imgSrc}</h2>
              <img alt="区块链部落" style={{
                  width: 1600
                }} src={"http://localhost:8080/ipfs/" + this.state.imgSrc}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}

export default App

9. 运行项目

  • npm start
  • 新建终端,启动节点服务ipfs daemon

上传图片到IPFS

10. 总结

这本文章主要复习如何创建React项目,如何安装ipfs-api,如何编写上传图片到IPFSPromise函数,下一篇我们将介绍,如何将图片hash存储到区块链,如何从区块链取到hash,并且通过hashipfs拿到图片。

11. 技术交流

  • 区块链技术交流QQ群:348924182
  • 进微信群请加微信:liyc1215
  • 「区块链部落」官方公众号

IPFS(InterPlanetary File System)是一个基于内容寻址的、分布式的、新型超媒体传输协议。IPFS支持创建完全分布式的应用。它旨在使网络更快、更安全、更开放。IPFS是一个分布式文件系统,它的目标是将所有计算设备连接到同一个文件系统,从而成为一个全球统一的存储系统。某种意义上讲,这与Web最初的目标非常相似,但是它是利用BitTorrent协议进行Git数据对象的交换来达到这一个目的的。IPFS正在成为现在互联网的一个子系统。IPFS有一个更加宏伟而疯狂的目标:补充和完善现有的互联网,甚至最终取代它,从而成为新一代的互联网。这听起来有些不可思议,甚至有些疯狂,但的确是IPFS正在做的事情。图1-1所示为IPFS的官方介绍。 图1-1 IPFS官方介绍IPFS项目通过整合已有的技术(BitTorrent、DHT、Git和SFS),创建一种点对点超媒体协议,试图打造一个更加快速、安全、开放的下一代互联网,实现互联网中永久可用、数据可以永久保存的全球文件存储系统。同时,该协议有内容寻址、版本化特性,尝试补充甚至最终取代伴随了我们20多年的超文本传输协议(即HTTP协议)。IPFS是一个协议,也是一个P2P网络,它类似于现在的BT网络,只是拥有更强大的功能,使得IPFS拥有可以取代HTTP的潜力。Filecoin是运行在IPFS上的一个激励层,是一个基于区块链的分布式存储网络,它把云存储变为一个算法市场,代币(FIL)在这里起到了很重要的作用。代币是沟通资源(存储和检索)使用者(IPFS用户)和资源的提供者(Filecoin矿工)之间的中介桥梁,Filecoin协议拥有两个交易市场—数据检索和数据存储,交易双方在市场里面提交自己的需求,达成交易。IPFS和Filecoin相互促进,共同成长,解决了互联网的数据存储和数据分发的问题,特别是对于无数的区块链项目,IPFS和Filecoin将作为一个基础设施存在。这就是为什么我们看到越来越多的区块链项目采取了IPFS作为存储解决方案,因为它提供了更加便宜、安全、可快速集成的存储解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎跃春

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值