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

上传图片到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中导入包,连接客户端)

    1
    2
    3
    import ipfsClient from 'ipfs-http-client'

    const ipfs = ipfsClient({ host: 'localhost', port: '9000', protocol: 'http' })
  3. 前端代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <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和结合就可以开发出不错的应用来,星空笔记就不错!


This page is synchronized from the post: ‘上传图片到IPFS网络 / 网络研习社#53’

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×