图片传输到ipfs节点然后将生成的ipfs访问链接存到区块链

ipfs 上存储图片并将返回的链接返回到区块链上

在区块链上直接存储图片不仅时间很长,而且需要进行分片和拼接,比较麻烦,我们直接使用ipfs存储图片

流程描述:

  1. 首先在本地搭建ipfs节点(可自行搜索:ipfs节点搭建),使用go-ipfs版本进行搭建,搭建完之后,使用ipfs daemon指令启动ipfs服务监听,同时占用8080端口。 使用时我们需要先打开ipfs服务,再启动项目,避免端口冲突。正确启动之后的命令行最后一行应该显示Daemon is ready
  2. 服务启动成功后,我们首先在我们的前端绑定一个input,这个input的type是file类型,同时指定一个id,我们通过这个id获取到这个文件(1)。然后将这个文件赋值(2)我们同时还需要将ipfs-http-client模块导入到我们使用的js中,生成一个ipfs对象.以便我们在saveImageOnIpfs中使用(3)

    1.<input type="file" class="form-control add_img" id="co_img" placeholder="Ex: 请选择图片">
    
    2.const file = document.getElementById("co_img").files[0];
    
    3.import { create } from 'ipfs-http-client';
     const ipfs = create({ host: 'localhost', port: '5001', protocol: 'http' });
  3. 实现这三步之后,我们相当于把文件取出来了,取出来之后,我们再把这个文件当成参数传到saveImageOnIpfs方法里,saveImageOnIpfs方法里有一个ipfs.add()方法,此方法就是将图片传输到ipfs上,同时返回传输回的结果,会有一个hash值返回,resolve函数可以将hash值作为返回值再传到.then里的函数的参数,然后拼接成一个类似这种的链接:即href,然后我们再在这个this函数里面调用App.addcollectionsUp方法把链接和相关数据上传到区块链上。

    uploadimg:async function(){
        const file = document.getElementById("co_img").files[0];
        console.log(file)
        if(file==null){
            alert("未选择文件");
        }
        const httpGateway = 'https://127.0.0.1:8080'
        this.saveImageOnIpfs(file).then(function(hash){
            //这里就把图片的hash取出来之后同时拼接到了链接后面
            const href = `${httpGateway}/ipfs/${hash}`
            img_href = href;
            console.log(img_href);
            App.addcollectionsUp();
        })
    },
    saveImageOnIpfs: function(input) {
        return new Promise(async(resolve, reject) => {
            try {
                //ipfs的add方法是将东西添加到ipfs网络上
                let results = await ipfs.add(input);
                let hash1 = results.path;
                resolve(hash1);
            } catch (err) {
                console.error(err);
                reject(err);
            }
        })
    },
  4. addcollectionsUp函数定义如下:

    addcollectionsUp: async function() {
           let _conum = $("#co_num").val();
           // console.log(img_href);
           let _coprice = $("#co_price").val();
           let  _coname = $("#co_name").val();
           let _cointro = $("#co_intro").val();
           const { addCollectionUp } = this.meta.methods;
           let result = await addCollectionUp(_conum, _coprice, _coname,_cointro,img_href).send({ from: this.account });
           console.log(result);
           window.location.reload(); 
       },

    我们只需要把生成的href赋值给img_href就可以直接传到区块链上了。然后再取出来在前端渲染即可。

本文参与2022世界杯预选赛赛程直播社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

  • 发表于 2022-03-18 23:37
  • 阅读 ( 478 )
  • 学分 ( 13 )
  • 分类:IPFS

0 条评论

请先 登录 后评论
链链不忘
链链不忘

2 篇文章, 18 学分