Search code examples
javascriptnode.jsipfsjs-ipfs

IPFS: base64-encoded image not showing as image


I have a simple function that tries to base64-encode an image and upload it to IPFS:

async function toIPFS() {
  const node = await IPFS.create()
  const data = fs.readFileSync('./src/assets/logo.png', 'base64').toString('base64')
  const results = await node.add(data)
  console.log(results.cid.string)
}

However, when I actually check the hash it displays as a long string:

iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHB...etc

How do I upload an image such that it actually displays as an image? What am I missing?

I've never worked with images so pardon if this is a noob question:)


Solution

  • What you're seeing returned is the file encoded as base64, if you want to store the image itself for later retrieval, this is how you'd do it:

    async function toIPFS() {
         const node = await IPFS.create()
         const data = fs.readFileSync('./src/assets/logo.png')
         const results = await node.add(data)
         console.log(results.cid.string)
    }