Previous posts:
- How to push/load image file from/to IPFS using Javascript. Examples (PART I)
- How to push/load image file from/to IPFS using Javascript. Examples (PART II)
- How to push/load image file from/to IPFS using Javascript. Examples (PART III)
In this post, we want to show how IPFS works using only HTML and Javascript (This is not another Node.js server example code…)
In this example we get PNG image files from the HASH and we read it as base64 and transform in a BLOB and in a link . ( see it working)
The code is similar to the previous post.
Continuing, if you inspect the code, you will see we load always the script resource:
https://unpkg.com/ipfs/dist/index.js
We use this code to get the HASH param from the Query_URL_String, obtain the IPFS png file in base64, transform it in a BLOB object and in a link (visible in a img HTML tag object)
var input, file, fr; const repoPath = 'ipfs-1111' //+ Math.random() const ipfs = new Ipfs({ repo: repoPath }) function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } ipfs.on('ready', () => { //link example: https://raulikidj.club/examples/ipfs/ipfsimg.html?HASH=QmVBJzBwmqvckVd5eFWjwhB7w16ZXyh1ANCcT5rhFDRRg2 //input = 'QmVBJzBwmqvckVd5eFWjwhB7w16ZXyh1ANCcT5rhFDRRg2' input = getParameterByName('HASH'); ipfs.files.cat(input, function (err, file) { if (err) { throw err } img = file.toString("base64"); //document.write("<img src="image/png;base64," />"); function dataURItoBlob(dataURI) { var byteString = atob(dataURI.split(',')[1]); var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i less_than byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ab], { type: 'image/png' }); } bloby = dataURItoBlob("data:image/png;base64," + img) var reader = new FileReader(); reader.onload = function(e){ window.location.href = reader.result; } var url = window.URL.createObjectURL(bloby); //window.location.href = url; log("Image src link (generated dynamically) created once obtained the base64 content of the image from IPFS:"); log(url); document.getElementById("design_display").src=url; }) const log = (line) => { document.getElementById('output').appendChild(document.createTextNode(`${line}\r\n`)) } })
IMPORTANT NOTE!!: Obtain the source code from the example, not from the web, because WordPress changes the tags for strange chars to avoid javascript. For this reason there is “less_than” in the code instead of < ,etc… very ugly WordPress team…
By MrAddon
Here a more actually example of IPFS communication using HTML and Javascript
https://mraddon.blog/2019/04/29/html-and-javascript-code-to-load-a-file-in-your-ipfs-server/
LikeLike