lfx区块链博客


lfx 微信:chen1048258,全球区块链职业教育布道师,通信和信息技术培养工程区块链高级授课专家。


微信
技术交流群

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

目录

系列文章

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= 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= 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
  • 「区块链部落」官方公众号

版权声明:博客中的文章版权归博主所有,未经授权,禁止转载,转载请注明出处,合作请联系:chen1048258(微信)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦