在区块链上直接存储图片不仅时间很长,而且需要进行分片和拼接,比较麻烦,我们直接使用ipfs存储图片
流程描述:
-
首先在本地搭建ipfs节点,使用go-ipfs版本进行搭建,搭建完之后,使用 ipfs daemon指令启动ipfs服务监听,同时占用8080端口。
使用时我们需要先打开ipfs服务,再启动项目,避免端口冲突。正确启动之后的命令行应该如下图所示。
-
服务启动成功后,我们首先在我们的前端绑定一个input,这个input的type是file类型,同时指定一个id,我们通过这个id获取到这个文件(1)。然后将这个文件赋值(2)
1.<input type="file" class="form-control add_img" id="co_img" placeholder="Ex: 请选择图片"> 2.const file = document.getElementById("co_img").files[0];
-
实现这两步之后,我们相当于把文件取出来了,取出来之后,我们再把这个文件当成参数传到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 = 'http://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); } }) },
-
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就可以直接传到区块链上了。然后再取出来在前端渲染即可。