天天看點

docker 部署ipfs節點并使用nodejs進行上傳測試

docker 部署ipfs節點

# 建立docker ipfs 映射目錄
% mkidr -p /Users/domino/files/ipfs/ipfs_node/ipfs_data
% mkdir -p /Users/domino/files/ipfs/ipfs_node/ipfs_staging

# 建立臨時變量
% export ipfs_staging=/Users/jiangwujie/files/ipfs/ipfs_node/ipfs_staging
% export ipfs_data=/Users/jiangwujie/files/ipfs/ipfs_node/ipfs_data

# docker 啟動 ipfs節點
% docker run -d --name ipfs_host -v $ipfs_staging:/export -v $ipfs_data:/data/ipfs -p 4001:4001 -p 8080:8080 -p 5001:5001 ipfs/go-ipfs:latest
# 檢視ipfs容器
% docker ps
CONTAINER ID   IMAGE                                       COMMAND                  CREATED          STATUS                    PORTS                                                                                        NAMES
24b518cb8ad9   ipfs/go-ipfs:latest                         "/sbin/tini -- /usr/…"   35 minutes ago   Up 35 minutes (healthy)   0.0.0.0:4001->4001/tcp, 0.0.0.0:5001->5001/tcp, 4001/udp, 0.0.0.0:8080->8080/tcp, 8081/tcp   ipfs_host
           

使用nodejs進行本地圖檔上傳測試

const ipfsAPI = require('ipfs-api');

// create an instance of the ipfs api client with the address of the local node
const ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'});

// read the image file from disk
const fs = require('fs');
const file = fs.readFileSync('/Users/domino/Downloads/jiagoutu.png');

// add the file to IPFS
ipfs.add(file, (err, result) => {
    if (err) {
        console.error(err);
        return;
    }

    console.log('Image uploaded to IPFS. IPFS hash:', result[0].hash);
});
           

執行測試,可以看到上傳成功

% node src/testipfs.js 
{
  'api-path': '/api/v0/',
  'user-agent': '/node-ipfs-api/26.1.2/',
  host: 'localhost',
  port: '5001',
  protocol: 'http'
}
Image uploaded to IPFS. IPFS hash: QmRXxBUN7rpGKRrE8sVxA5vzUd9JQTi4kDu2Nc4WctqaHX

           

使用這個hash值在浏覽器上可以正常的擷取圖檔進行展示

url為:

http://localhost:8080/ipfs/{hash值}

如:

http://localhost:8080/ipfs/QmRXxBUN7rpGKRrE8sVxA5vzUd9JQTi4kDu2Nc4WctqaHX

docker 部署ipfs節點并使用nodejs進行上傳測試

參考文檔:

  • https://blog.csdn.net/kk3909/article/details/104814337

繼續閱讀