lemooljiang avatar

上传图片到IPFS网络 / 网络研习社#53

lemooljiang

Published: 17 Dec 2019 › Updated: 17 Dec 2019

上传图片到IPFS网络 / 网络研习社#53

ipfs

在上一篇《零代码用IPFS做文件服务器》中启动了IPFS网络,这时服务器这边就准备好了,前端就可以向IPFS网络上传图片了。

关键的函数只有一个ipfs.add,前端读取图片,用ipfs.add上传,得到一个文件的哈希值,再在前端展示就好啰。

js-ipfs-http-client

  1. 前端和IPFS网络交互需要用到客户端插件js-ipfs-http-client,一条命令就可以安装好,cnpm install ipfs-http-client --save
  2. 必要的设置(vue中导入包,连接客户端)
import ipfsClient from 'ipfs-http-client'

const ipfs = ipfsClient({ host: 'localhost', port: '9000', protocol: 'http' })
  1. 前端代码
<label id="file2">Choose file to upload</label>
<input type="file" ref="file" id="file" name="file" multiple="multiple"/>
<input type="submit" @click="upload">

methods:{
upload() {
  let that = this
  let saveImageOnIpfs = (reader) => {
    return new Promise(function(resolve, reject) {
      const buffer = Buffer.from(reader.result)
      that.ipfs.add(buffer).then((response) => {
        console.log(response)
        resolve(response[0].hash)
      }).catch((err) => {
        console.error(err)
        reject(err)
      })
    })
  }

  let file = this.$refs.file.files[0]
  console.log(123, file)
  let reader = new FileReader()
  reader.readAsArrayBuffer(file)

  reader.onloadend = function (e) {
    console.log(233, reader)
    saveImageOnIpfs(reader).then((hash) => {
      console.log(655, hash) 
    })
  }
 }
}

上传图片就这么几行代码就可以搞定,比起PHP等来还是有一定的优势,至少看起来简单。再说,IPFS和区块链连接紧密,是天生的盟友,比如Steem 和IPFS和结合就可以开发出不错的应用来,星空笔记就不错!

Leave 上传图片到IPFS网络 / 网络研习社#53 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #steemjiang posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang