Created
March 13, 2018 07:03
-
-
Save estebanrfp/de6ae3f9f8d748182158bca1c0ac492d to your computer and use it in GitHub Desktop.
Browser to IPFS Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>JavaScript file upload</title> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<script src="https://wzrd.in/standalone/buffer"></script> | |
<script src="https://unpkg.com/[email protected]/dist/index.js" | |
integrity="sha384-5bXRcW9kyxxnSMbOoHzraqa7Z0PQWIao+cgeg327zit1hz5LZCEbIMx/LWKPReuB" | |
crossorigin="anonymous"></script> | |
</head> | |
<script type="text/javascript"> | |
function upload() { | |
const reader = new FileReader(); | |
reader.onloadend = function() { | |
const ipfs = window.IpfsApi('localhost', 5001) // Connect to IPFS | |
const buf = buffer.Buffer(reader.result) // Convert data into buffer | |
ipfs.files.add(buf, (err, result) => { // Upload buffer to IPFS | |
if(err) { | |
console.error(err) | |
return | |
} | |
let url = `https://ipfs.io/ipfs/${result[0].hash}` | |
console.log(`Url --> ${url}`) | |
document.getElementById("url").innerHTML= url | |
document.getElementById("url").href= url | |
document.getElementById("output").src = url | |
}) | |
} | |
const photo = document.getElementById("photo"); | |
reader.readAsArrayBuffer(photo.files[0]); // Read Provided File | |
} | |
</script> | |
<body> | |
<form action="/"> | |
<fieldset> | |
<legend>Upload photo</legend> | |
<input type="file" name="photo" id="photo"> | |
<button type="button" onclick="upload()">Upload</button> | |
</fieldset> | |
</form> | |
</br> | |
</br> | |
<a id="url"></a> | |
</br> | |
</br> | |
<img id="output"> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment