Blob creating function in javascript saving multiple files - javascript

Can someone explain to me how this piece of code works. Also, the output is not what I want. It saves 2 files instead of 1.
Javascript
function saveTextAsFile() {
var textToWrite = document.getElementById('textArea').innerHTML;
var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
var fileNameToSaveAs = "file.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
HTML
<button id="save" onclick="saveTextAsFile()">Save</button>
<textarea id="textArea" class="Textarea" placeholder="Click to Type" cols="20"></textarea>

You code does NOT work:
textarea input values are read with .value not .innerHTML, you where getting no output so
change:
var textToWrite = document.getElementById('textArea').innerHTML;
into
var textToWrite = document.getElementById('textArea').value;
You get 2 files because you made 2 same events on same button that call same function, remove one of those:
<button id="save" onclick="saveTextAsFile()">Save</button>
here remove onclick="saveTextAsFile()" or remove this two lines:
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
This will fix your errors, and as far how whole code works, this is not code review site, for that visit https://codereview.stackexchange.com/ or google each command and read its definitions.

Related

Save options from a select to file with JS

Hello I have a select and an input button to browse files, and i would love to save the options in the select to a text file in the format:
line1
line2
line3
...
I have read this tutorial:
Save <Select >Tag values into text file
But it does not seem to work. When i save, the options are written in the same line and only the first word for the option value is writte to the file.
I.E. my options are:
buy food
call john
print documents
the output in the file is:
buy call print
The code i use is:
var textToWrite = "";
$('#todolist>option').each(function () {
textToWrite += this.value + "\n";
});
var textFileAsBlob = new Blob([textToWrite], {type: 'text/plain'});
var fileNameToSaveAs = "directive.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
console.log("innerHTML -> " + downloadLink.innerHTML);
window.webkitURL != null;
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();
}
var button = document.getElementById('file-save');
button.addEventListener('click', saveTextAsFile);
I am using google's link for jquery:
Can anybody help? Thanks in advance
So you want also the text, not only the values?
$('#todolist>option').each(function () {
textToWrite += this.value + "\n" + this.innerText + "\n";
});

Save A String to a Text File

I have this simple html and css code
function saveTextAsFile() {
var textToWrite = document.getElementById('textArea').value;
var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
var fileNameToSaveAs = "untitled.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);
destroyClickedElement = (event) => { document.body.removeChild(event.target); }
<textarea id="textArea"></textarea>
<button type="button" value="save" id="save">Save</button>
The JavaScript code works as i want, when i click on save button it saves a file with name "untitiled.txt" for me, but for some reason firstly this code doesn't work on this stackoverflow snippet section & secondly, is there any other way to save a file with text from the textArea inside it ?
Like i don't want to do this appendChild and all

HTML Editor with Download Option

I'm looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>. Are there any features in JS that would work similar to this? (HTML Format!!)
var x = document.write("<p>Hi!</p>");
window.replace(x);
And then:
<button onclick="open()">Save</button>
<script>
var hi = document.write("<p>hi</p>;");
open() {
window.open(hi)
}
</script>
After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas?
Thanks in advance.
<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea><br/><br/>
<input type="button" id="dwn-btn" value="Save" />
<script>
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function() {
var text = document.getElementById("text-val").value;
var filename = "example.html";
download(filename, text);
}, false);
</script>
I hope this is what you are expecting
Create new Blob from your html script with application/octet-stream mime type. Then use URL.createOjectURL api to generate download link. And navigate to that link. In this example code I navigated using creating temporary link (<a>) element.
function download() {
var blobPart = ['<h1>Test</h1>'];
var blob = new Blob(blobPart, {
type: "application/octet-stream"
});
var urlObj = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.href = urlObj;
a.download = 'filename.html';
a.click();
a.remove();
}
document.getElementById('download-btn').addEventListener('click', download);
Download

File Write Operation in javascript

I need to write into a file in javascript.I tried below Code.I got error like"FileWriter is not defined".please help me in this.
<html>
<head>
</head>
<body>
<input type = "button" value = "write" onclick="WriteFile()">
<script>
function WriteFile()
{
var fileWriter = new FileWriter("C:\Users\ananthi\Desktop\readme.txt");
fileWriter.open() ;
fileWriter.writeLine("Another line") ;
fileWriter.close() ;
}
</script>
</body>
</html>
If you would like to use button call function:
<input type = "button" value = "write" onclick="Download()">
Download () {
let filename = "readme.txt";
let text = "Text of the file goes here.\n1";
let blob = new Blob([text], {type:'text/plain'});
let link = document.createElement("a");
link.download = filename;
//link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}, 100);
}
The File Writer API is defunct and never saw significant browser support.
You cannot write files from browser-based JavaScript. What you do instead is provide the user with a link that they can download, like this:
var filename = "readme.txt";
var text = "Text of the file goes here.";
var blob = new Blob([text], {type:'text/plain'});
var link = document.createElement("a");
link.download = filename;
link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
That works on browsers that support the File API (which modern ones do, but not IE9 or earlier).

Convert a base64 to a file in Javascript

The goal is to transform a base64 string into a sendable jpg file, I cant use the html input type file but i have to serve in the same format. I am bit lost with file generation. (I am on a client side mobile app).
This is what i have:
file = "data:image/jpg;base64,#{imageData}"
imageData is the base64 string
There is a way to transform this into a valid file?
Disclaimer: Produces an invalid result (close, but invalid)
I've done the reverse earlier last week - that is, load an image as binary data (to get around the requirement to run file from localhost).
In it, I:
loaded the file
base64 converted it
added a pre-amble to the base64 string
set the constructed string to be the src of an img element
This worked just fine. Upon reading your question, I tried to simply reverse the process. I was however, unsuccessfull somewhere. The data is extracted from the image correctly, then somewhere afterwards (I think in the call to atob that un-encodes it) the data is messed-up.
The saved files are an unexpected size, have an added char before "%PNG" and have some missing data in the middle of the file. I'm rather perplexed at this point, to be honest.
Anyhow, here's the code I've tried:
1. Code to read a file and stuff the data into an element
// fileVar is an object as returned by <input type='file'>
// imgElem is an <img> element - (doesn't need to be added to the DOM)
function loadImgFromFile(fileVar, imgElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
imgElem.src = result;
}
}
2. Attempt to grab data from an image/canvas and force the download of it using a programmer-supplied filename.
<!doctype html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onPageLoaded, false);
function onPageLoaded(evt)
{
var imgElem = byId('srcImg');
imgElem.onload = function(){saveImgAsFile( byId('srcImg'), "myImage.png" );};
// simple result of canvas.toDataURL() called on a 5x5 pixel image of a '+'
imgElem.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2NkQID/QCYjiAsmoABFEMRBAThVYmgHAAhoBQWHhfyYAAAAAElFTkSuQmCC";
// use the below line instead of the one above, if you wish to assign an actual image file, rather than the result of call to canvas.toDataURL()
// the base64 string allows me to keep it all in the one file, also, to run if opened via a double-click, rather than having to run from localhost
// imgElem.src = "img/1x1.png";
}
function saveImgAsFile(imgElem, fileName)
{
// get a base64 encoded string from an image element
var srcElem = imgElem;
var dstCanvas = newEl('canvas');
dstCanvas.width = srcElem.naturalWidth;
dstCanvas.height = srcElem.naturalHeight;
var ctx = dstCanvas.getContext('2d');
ctx.drawImage(srcElem,0,0);
var imgSrcStr = dstCanvas.toDataURL();
// extract the image type
var colonPos = imgSrcStr.indexOf(":");
var semiColonPos = imgSrcStr.indexOf(";");
var imgType = imgSrcStr.slice(colonPos+1, semiColonPos);
console.log("image type: " + imgType);
// extract the image data
var commaPos = imgSrcStr.indexOf(',');
var base64ImgString = imgSrcStr.slice(commaPos + 1);
console.log("Data: " + base64ImgString);
// holds the data that is actually written to disk for this image
//** I think the error occurs during this step **//
var unencodedImage = atob(base64ImgString);
var imgFileAsBlob = new Blob( [unencodedImage], {type: imgType} );
var fileNameToUse = fileName;
var downloadLink = newEl('a');
downloadLink.download = fileNameToUse;
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(imgFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(imgFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
/*
function saveTextAsFile()
{
var textToWrite = "This is just some random content";
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'})
var fileNameToSaveAs = "myFile.txt";
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);
}
</script>
</head>
<body>
<img id='srcImg'/>
</body>
</html>

Categories

Resources