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
Related
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.
I have created a simple HTML file that has a textarea, two text input, and a button that when the button is clicked it downloads what is in the textarea with what is in the text input as the name. This has worked for me a very long time until I typed text with a #. When I put the # it would create the txt file with only the stuff before the #. This is the code for how I download it.
function generate() {
var textToSave = document.getElementById('Input1').value;
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = document.getElementById('fileName').value+'.' + document.getElementById("fileExtension").value;
hiddenElement.click();
}
I can't use anything but the #, so I need a way for the file to keep all the text.
You should try with a blob :
var textToSave = document.getElementById('Input1').value;
var hiddenElement = document.createElement('a');
hiddenElement.download = 'string.txt';
var blob = new Blob([textToSave], {
type: 'text/plain'
});
hiddenElement.href = window.URL.createObjectURL(blob);
hiddenElement.click();
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
Let´s say I have an audio file recorded by a user in the browser. I would like to
get the file
load the file into input of a form
Some older posts talk about how this is not possible due to security issues, but now it is a possibility according to this answer: how to set file input after file drop
form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<div class='col-sm-6' style="padding-left:0px;" >
<form action="/main/" method="post" id="my_form" enctype="multipart/form-data">
{% csrf_token %}
<div> <input type="file" name="audio" id="id_audio" /> </div>
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<input class="btn btn-success" type="submit" name="submit" value="Gem" />
</form>
</div>
audio file:
<ol id="recordingsList">
<li id="myfile">
<audio controls="" src="blob:http://127.0.0.1:8000/99888"></audio>
myaudiofile.wav
</li>
</ol>
function to create the audio control and link to download the file, I want to append the file to id_audio input in the form:
<script>
function createDownloadLink(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
var li = document.createElement('li');
var link = document.createElement('a');
$(li).attr('id', 'recordedaudio-id');
$(link).attr('id', 'savetodisk');
//name of .wav file to use during upload and download (without extendion)
var filename = new Date().toISOString();
//add controls to the <audio> element
au.controls = true;
au.src = url;
//save to disk link
link.href = url;
link.download = filename+".wav"; //download forces the browser to donwload the file using the filename
link.innerHTML = "Save to disk";
//add the new audio element to li
li.appendChild(au);
//add the filename to the li
li.appendChild(document.createTextNode(filename+".wav "))
//add the save to disk link to li
li.appendChild(link);
//upload link
var upload = document.createElement('a');
upload.href="#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, filename);
xhr.open("POST","upload.php",true);
xhr.send(fd);
})
li.appendChild(document.createTextNode (" "))//add a space in between
li.appendChild(upload)//add the upload link to li
recordingsList.appendChild(li);
var fileElement = $('#myfile');
var audioFormElement = $('#id_audio');
// get the audio file from fileElement
// set audio file in audioFormElement
}
</script>
Based on the MediaRecorder API (https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder), possible solution:
Store it locally:
<script>
var handleSuccess = function(stream) {
var link = document.createElement('a');
link.textContent = 'Download';
link.target = '_blank';
link.setAttribute("download", 'audio_1.ogg');
if (window.URL) {
link.href = window.URL.createObjectURL(stream);
} else {
link.href = stream;
}
// Append <a> to where you want to.
};
</script>
Upload it using XMLHttpRequest:
var chunks = [];
var handleSuccess = function(stream) {
var mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
};
mediaRecorder.requestData();
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
var xhr = new XMLHttpRequest();
xhr.onload = function(e) {
if(this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var formData = new FormData();
formData.append("audio_data", blob, 'audio_1.ogg');
xhr.open("POST", "upload.php", true);
xhr.send(formData);
}
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).