基于js-ipfs-api实现ipfs的文件上传与下载

配置本地的ipfs节点

ipfs官网:https://ipfs.io/
下载地址:https://dist.ipfs.io/#go-ipfs

# 初始化ipfs节点
ipfs init
# 运行ipfs节点
ipfs daemon

更多配置可参考:
https://ipfs.io/docs/getting-started/
https://hacpai.com/article/1511015097370
http://liyuechun.org/2017/11/20/ipfs-blockchain/

使用js-ipfs-api调用ipfs服务

连接本地ipfs节点

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

本地文件上传到ipfs,并获取hash

ipfs.add(fs.readFileSync(path), function (err, files) {
     if (err || typeof files == "undefined") {
         console.log(err);
     } else {
         console.log(files);
     }
 })

通过hash从ipfs获取数据,并保存为本地文件

ipfs.get(hash,function (err,files) {
     if (err || typeof files == "undefined") {
         console.log(err);
     } else {
         console.log(files);
     }
 })

使用promise进行封装调用

ipfsFile.js

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

exports.add = (buffer) =>{
    return new Promise((resolve,reject)=>{
        try {
            ipfs.add(buffer, function (err, files) {
                if (err || typeof files == "undefined") {
                    reject(err);
                } else {
                    resolve(files[0].hash);
                }
            })
        }catch(ex) {
            reject(ex);
        }
    })
}
exports.get = (hash) =>{
    return new Promise((resolve,reject)=>{
        try{
            ipfs.get(hash,function (err,files) {
                if (err || typeof files == "undefined") {
                    reject(err);
                }else{
                    resolve(files[0].content);
                }
            })
        }catch (ex){
            reject(ex);
        }
    });
}

index.js

const ipfsFile = require('./ipfsFile');
const fs = require('fs');

//操作文件
let addPath = "./storage/add/onepiece.jpg";
let getPath = "./storage/get/onepiece.jpg";
let buff = fs.readFileSync(addPath);
ipfsFile.add(buff).then((hash)=>{
    console.log(hash);
    console.log("http://localhost:8080/ipfs/"+hash);
    return ipfsFile.get(hash);
}).then((buff)=>{
    fs.writeFileSync(getPath,buff);
    console.log("file:"+getPath);
}).catch((err)=>{
    console.log(err);
})

//操作内容
let User = {
    "name":"naruto",
    "age":23,
    "level":"ss"
};
buff = Buffer.from(JSON.stringify(User));
ipfsFile.add(buff).then((hash)=>{
    console.log(hash);
    console.log("http://localhost:8080/ipfs/"+hash);
    return ipfsFile.get(hash);
}).then((buff)=>{
    let obj = JSON.parse(buff.toString('utf-8'));
    console.log(obj);
}).catch((err)=>{
    console.log(err);
})

文本哈希值:QmRfhWo4c24MWYXLxu69FcJBnKpmnjY9mN5nMiK8U9zNxB
ipfs官方网关:https://ipfs.io/ipfs/QmRfhWo4c24MWYXLxu69FcJBnKpmnjY9mN5nMiK8U9zNxB

文件哈希值:QmVwdMZj5z1iSeKhmLPdZ6Diipn3krGZUnMLQMVxj4NjW7
ipfs官方网关:https://ipfs.io/ipfs/QmVwdMZj5z1iSeKhmLPdZ6Diipn3krGZUnMLQMVxj4NjW7

基于js-ipfs-api实现ipfs的文件上传与下载_第1张图片

你可能感兴趣的:(以太坊)