Search code examples
javascriptnode.jsxmlhttprequestmultipartform-dataipfs

How do I publish an Uint8Array to IPFS, using its HTTP API on both browser and node.js?


I've been trying to do so for several hours to no success. The relevant API endpoint is block/put. IT asks for the HTTP request to use multipart/form-data, but I'm not sure how to do it. Here is one attempt:

const req = require("xhr-request-promise");
const FormData = require("form-data");

(async () => {
  const form = new FormData();
  form.append("data", new Buffer([1, 2, 3]));
  console.log(await req("https://ipfs.infura.io:5001/api/v0/block/put", {
    method: "POST",
    body: form
  }));
})();

Solution

  • ipfs-http-client is perfect for this task:

    const { create } = require('ipfs-http-client');
    
    // connect to ipfs daemon API server
    const ipfs = create('https://ipfs.infura.io:5001');
    
    (async () => {
        await ipfs.block.put(new Uint8Array([1, 2, 3]));
    })();