ipfs存储和获取数据

安装ipfs-api

切换到项目根目录,安装ipfs-api

npm install --save ipfs-api

 

导入IPFS

const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});

 

上传大文本字符串到IPFS

saveTextBlobOnIpfs = (blob) => {
    return new Promise(function(resolve, reject) {
      const descBuffer = Buffer.from(blob, 'utf-8');
      ipfs.add(descBuffer).then((response) => {
        console.log(response)
        resolve(response[0].hash);
      }).catch((err) => {
        console.error(err)
        reject(err);
      })
    })
}

 

上传数据到IPFS

this.saveTextBlobOnIpfs(ipfsContent).then((hash) => {
    console.log(hash);
});

hash即是数据上传到IPFS后返回的HASH字符串

 

上传文件到IPFS

上传图片到IPFS的Promise函数

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.log(err)
      reject(err);
    })
  })
}

获取图片并上传

var file = this.$refs.files[0];
var reader = new FileReader();
// reader.readAsDataURL(file);//上传图片路径
reader.readAsArrayBuffer(file)//上传图片内容
reader.onloadend = (e) => {
   console.log(reader)
   this.saveImageOnIpfs(reader)
}

 

从IPFS读取数据

ipfs.cat(this.state.strHash).then((stream) => {
    console.log(stream);
    let strContent = Utf8ArrayToStr(stream);
    console.log(strContent);
});

streamUint8Array类型的数据,下面的方法是将Uint8Array转换为string字符串。

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
      {
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
          // 0xxxxxxx
          out += String.fromCharCode(c);
          break;
        case 12: case 13:
          // 110x xxxx   10xx xxxx
          char2 = array[i++];
          out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
          break;
        case 14:
          // 1110 xxxx  10xx xxxx  10xx xxxx
          char2 = array[i++];
          char3 = array[i++];
          out += String.fromCharCode(((c & 0x0F) << 12) |
                         ((char2 & 0x3F) << 6) |
                         ((char3 & 0x3F) << 0));
          break;
        default:
          break;
      }
    }

    return out;
}

 

转载于:https://www.cnblogs.com/yinian/p/9836740.html

你可能感兴趣的:(ipfs存储和获取数据)