JSFiddle - React, Tailwind, and code Playground
HTML
<table>
<tr>
<td colspan="3">Binary data:</td>
</tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs" /></td>
<td><button onclick="saveImage()">Save file</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad" /></td>
<td><button onclick="loadImage()">Load file</button></td>
</tr>
<tr>
<td colspan="3" id="imagePreview">
</td>
</tr>
</table>
CSS
#inputTextToSave {
width:512px;
height:256px;
}
#holder {
border: 10px dashed #ccc;
width: 300px;
height: 300px;
}
#holder.hover {
border: 10px dashed #333;
}
JavaScript
var contentType = '';
window.saveImage = function() {
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type: contentType});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL !== null) {
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else {
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
window.loadImage = function() {
var file = document.getElementById("fileToLoad").files[0];
var reader = new FileReader();
reader.onload = function(event) {
var data = event.target.result;
document.getElementById("inputTextToSave").value = data;
var imagePreview = document.getElementById("imagePreview");
imagePreview.innerHTML = '';
var dataURLReader = new FileReader();
dataURLReader.onload = function(event) {
// Parse image properties
var dataURL = event.target.result;
contentType = dataURL.split(",")[0].split(":")[1].split(";")[0];
var image = new Image();
image.src = dataURL;
image.onload = function() {
...