Skip to content

Instantly share code, notes, and snippets.

@marsrobertson
Created April 26, 2019 08:21
Show Gist options
  • Save marsrobertson/ce76e927975c58c572a1df9e503bf4b4 to your computer and use it in GitHub Desktop.
Save marsrobertson/ce76e927975c58c572a1df9e503bf4b4 to your computer and use it in GitHub Desktop.
<!--
REMEMBER TO UPDATE CORS USING "normal quotes"
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "GET", "POST", "OPTIONS"]'
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'
-->
<!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> --> <!-- no longer supported -->
<script src="https://bundle.run/buffer@5.2.1"></script>
<script src="https://unpkg.com/ipfs-http-client@30.1.3/dist/index.js"></script>
</head>
<script type="text/javascript">
function upload() {
const reader = new FileReader();
reader.onloadend = function() {
const ipfs = window.IpfsHttpClient('localhost', 5001) // Connect to IPFS
// const ipfs = window.IpfsHttpClient('ipfs.infura.io', '5001')
const buf = buffer.Buffer(reader.result) // Convert data into buffer
ipfs.add(buf, (err, result) => { // Upload buffer to IPFS
if(err) {
console.error(err)
return
}
let url = `https://gateway.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