Related
I want to Write Data to existing file using JavaScript.
I don't want to print it on console.
I want to Actually Write data to abc.txt.
I read many answered question but every where they are printing on console.
at some place they have given code but its not working.
So please can any one help me How to actually write data to File.
I referred the code but its not working:
its giving error:
Uncaught TypeError: Illegal constructor
on chrome and
SecurityError: The operation is insecure.
on Mozilla
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
So can we actually write data to file using only Javascript or NOT?
You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
Some suggestions for this -
If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
To store some information on the client side that is considerably small, you can go for cookies.
Using the HTML5 API for Local Storage.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.
But if you want to write data, and enable user to download as a file to local. the following code works:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:
download('the content of the file', 'filename.txt', 'text/plain');
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
If you want to download binary data look here
Update
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Above answer is useful but, I found code which helps you to download text file directly on button click.
In this code you can also change filename as you wish. It's pure javascript function with HTML5.
Works for me!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
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();
}
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file
In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
function download() {
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {
download()
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>
Use the code by the user #useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file.
If you want to download the file automatically, pass the textFile that was just generated to this function:
var downloadFile = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language.
Save the code below to a text file
Change the file extension from '.txt' to '.html'
Right-click > Open With... > notepad
Program word processing as needed, then save
Double-click html file to open in default browser
Result will be previewed in the black box, click download to get the resulting text file
Code:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// do text manipulation here
let string1 = 'test\r\n';
let string2 = 'export.';
// assemble final string
const finalText = string1 + string2;
// convert to blob
const data = new Blob([finalText], {type: 'text/plain'});
// create file link
const link = document.createElement('a');
link.innerHTML = 'download';
link.setAttribute('download', 'data.txt');
link.href = window.URL.createObjectURL(data);
document.body.appendChild(link);
// preview the output in a paragraph
const htmlBreak = string => {
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
const preview = document.createElement('p');
preview.innerHTML = htmlBreak(finalText);
preview.style.border = "1px solid black";
document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>
I am new to javascript . all codes available on the internet related to create text file using javascript is not working in my laptop. can anybody give me idea or with possible code.
This code should work, give this a try and if this doesn't work then it may be an issue with your browser:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
And the HTML:
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
Taken from this Fiddle:
http://jsfiddle.net/uselesscode/qm5ag/
A very fast and easy solution is to use FileSaver.js :
https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js
Then it takes only 2 lines of code to download a txt file :
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
This code example will display a dialog box to download a file named "hello world.txt" containing the text "Hello, world!". Just replace this by the file name and the text content of your choice !
I have a HTML form to upload a file.
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
Then, I want to send a POST request to the server using this String.
Any idea how I can do that?
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
I don't think you really mean you want to submit the form (as in, send it to the server) at this stage.
Then, I want to send a POST request to the server using this String.
You can do that on browsers that support the File API, which is most modern ones but not IE8 or IE9. There's an example in this answer.
Basically, you get the File instance from your <input type="file"> element's files list, check its name, read it, and then post it:
Complete Example (source) (other than the POST bit, which I assume you know how to do):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<input type="file">
<button>Go</button>
<script>
(function() {
"use strict";
// Get our input element and our button; in this example there's
// just one of each, you'd narrow down these selectors of course
var inputElement = document.querySelector("input[type=file]"),
button = document.querySelector("button");
if (typeof FileReader !== 'function') {
alert("The file API isn't supported on this browser.");
inputElement.style.display = button.style.display = "none";
return;
}
if (!inputElement.files) {
alert("Odd, this browser has FileReader but no `files` property on the input element.");
inputElement.style.display = button.style.display = "none";
return;
}
button.addEventListener("click", function() {
var file, filename, reader, filedata;
// Does it have any files?
if (inputElement.files.length === 0) {
alert("No file chosen");
return;
}
// Get its first file
file = inputElement.files[0];
// Get its name in lower case
filename = file.name.toLowerCase();
// XML extension?
if (filename.substr(-4) !== ".xml") {
alert("Please only choose .xml files");
}
else {
// Yes, read it
reader = new FileReader();
reader.onload = function() {
// Get the file data, note that this happens asynchronously
filedata = reader.result;
// Send your POST with the data; here, we'll just dump it out
// as text
displayXml(filedata);
};
reader.readAsText(file); // or you can use readAsBinaryString
}
}, false);
function displayXml(xmlText) {
var pre = document.createElement('pre');
pre.innerHTML = xmlText.replace(/&/g, "&").replace(/</g, "<");
document.body.appendChild(pre);
}
})();
</script>
</body>
</html>
I have one download button created in JavaScript that links to particular file.
var strDownloadButton = "<br/><INPUT type="button" value="Download" onclick="add()"/>"
window.location.href = "/images/image1.jpg";
I have to rename the file image1 to image2 before downloading, so I use:
<a href="/images/image1.jpg" download="image2" >Download</a>
The problem is that there are 2 download buttons created (HTML5 download attribute created 1 more).
Is there any way to use the same button created by JavaScript, and refer into download attribute?
I have no idea what are you doing Brad Christie,
<a id="download" href="Chrysanthemum.jpg" download="image2" >Download</a>
document.getElementById("download").setAttribute("download", "image3")
here, you have an element that you want to download, you get the element and change its download attribute.
I'm not 100% sure it'll work, but I've done something like this before to download a resource and rename it using javascript. It does, however, mean the resource has to be on the same domain as the page otherwise you will run into a cross-domain security issue. Also, please excuse the fact that I'm using jQuery, but if you need to go without I'll let you look up how to make a cross-browser AJAX call.
With that said:
<!-- your anchor decorated with data-saveas -->
Download
<!-- wiring it up using jQuery/AJAX/Blob -->
<script type="text/javascript">
// Helper to convert AJAX response in to a BLOB
function dataToBlob(data, mimeString){
// convert data to ArrayBuffer
var buffer = new Int8Array(new ArrayBuffer(data.length));
for (var i = 0; i < data.length; i++){
buffer[i] = data.charCodeAt(i) & 0xff;
}
// http://stackoverflow.com/a/15302872/298053
try {
return new Blob([buffer],{type:mimeString});
} catch (e1) {
try {
var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder){
bb = new BlobBuilder();
bb.append([buffer.buffer]);
return bb.getBlob(mimeString);
} else if (e.name == 'InvalidStateError'){
return new Blob([buffer.buffer],{type:mimeString});
}
} catch (e2) {
}
}
return null;
}
// iterate over all the items that are marked as saveas
$('a[data-saveas]').each(function(){
var $this = $(this);
// Get the actual path and the destined name
var target = $this.prop('href'),
saveas = $this.data('saveas');
// make an ajax call to retrieve the resource
$.ajax({
url: target,
type: 'GET',
mimeType: 'text/plain; charset=x-user-defined'
}).done(function(data, textStatus, jqXHR){
var mimeString = jqXHR.getResponseHeader('Content-Type'),
blob = dataToBlob(data, mimeString);
if (blob){
// now modfy the anchor to use the blob instead of the default href
var filename = saveas,
href = (window.webkitURL || window.URL).createObjectURL(blob);
$this.prop({
'download': saveas,
'href': href,
'draggable': true
}).data({
'downloadurl': [mimeString, filename, href].join(':')
});
}
});
});
</script>
Not tested, but should work. Basically, you can go fetch the resource using jQuery and store it in to a blob with an assigned name. If it's able to do so, the link now becomes a custom-named blob resource with the provided name. if it can't the default functionality is retained and the user needs to name it his/herself.
There's already a solution for writing file JSON online but I want to save json file locally.
I've tried to use this example http://jsfiddle.net/RZBbY/10/
It creates a link to download the file, using this call
a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show();
Is there a way to save the file locally instead of providing a downloadable link?
There are other types of conversion beyond data:application/x-json;base64?
Here's my code:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Default functionality</title>
<link rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css">
<script src="http://jqueryui.com//jquery-1.7.2.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.core.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.widget.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.mouse.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.sortable.js"></script>
<script src="http://jqueryui.com/ui/jquery.ui.accordion.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/demos/demos.css">
<meta charset="utf-8">
<style>a { font: 12px Arial; color: #ac9095; }</style>
<script type='text/javascript'>
$(document).ready(function() {
var f = $('form'), a = $('a'),
i = $('input'), t = $('textarea');
$('#salva').click(function() {
var o = {}, v = t.val();
a.hide();//nasconde il contenuto
i.each(function() {
o[this.name] = $(this).val(); });
if (v === '') {
t.val("[\n " + JSON.stringify(o) + " \n]")
}
else {
t.val(v.substr(0, v.length - 3));
t.val(t.val() + ",\n " + JSON.stringify(o) + " \n]")
}
});
});
$('#esporta').bind('click', function() {
a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show();
});
</script>
</head>
<body>
<form>
<label>Nome</label> <input type="text" name="nome"><br />
<label>Cognome</label> <input type="text" name="cognome">
<button type="button" id="salva">Salva</button>
</form>
<textarea rows="10" cols="60"></textarea><br />
<button type="button" id="esporta">Esporta dati</button>
Scarica Dati
</body>
</html>
Based on http://html5-demos.appspot.com/static/a.download.html:
var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();
Modified the original fiddle: http://jsfiddle.net/9av2mfjx/
You should check the download attribute and the window.URL method because the download attribute doesn't seem to like data URI.
This example by Google is pretty much what you are trying to do.
It is not possible to save file locally without involving the local client (browser machine) as I could be a great threat to client machine. You can use link to download that file. If you want to store something like Json data on local machine you can use LocalStorage provided by the browsers, Web Storage
The possible ways to create and save files in Javascript are:
Use a library called FileSaver
saveAs(new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"}));
Create a blob object and offer a “save as”.
var a = document.createElement("a");
a.href = window.URL.createObjectURL(new Blob(["CONTENT"], {type: "text/plain"}));
a.download = "demo.txt";
a.click();
Upload the data, save it on the server.
var data = new FormData();
data.append("upfile", new Blob(["CONTENT"], {type: "text/plain"}));
fetch("SERVER.SCRIPT", { method: "POST", body: data });
Create a writable file stream.
const fileHandle = await window.showSaveFilePicker();
const fileStream = await fileHandle.createWritable();
await fileStream.write(new Blob(["CONTENT"], {type: "text/plain"}));
await fileStream.close();
In NodeJS, simply use the file system module
require("fs").writeFile("demo.txt", "Foo bar!");
<!-- (A) LOAD FILE SAVER -->
<!-- https://cdnjs.com/libraries/FileSaver.js -->
<!-- https://github.com/eligrey/FileSaver.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script>
// (B) "SAVE AS"
var myFile = new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"});
saveAs(myFile);
</script>
// (A) CREATE BLOB OBJECT
var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
// (B) CREATE DOWNLOAD LINK
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "demo.txt";
// (C) "FORCE DOWNLOAD"
// NOTE: MAY NOT ALWAYS WORK DUE TO BROWSER SECURITY
// BETTER TO LET USERS CLICK ON THEIR OWN
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);
<script>
function blobajax () {
// (A) CREATE BLOB OBJECT
var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
// (B) FORM DATA
var data = new FormData();
data.append("upfile", myBlob);
// (C) AJAX UPLOAD TO SERVER
fetch("3b-upload.php", {
method: "POST",
body: data
})
.then((res) => { return res.text(); })
.then((txt) => { console.log(txt); });
}
</script>
<input type="button" value="Go" onclick="blobajax()"/>
<script>
async function saveFile() {
// (A) CREATE BLOB OBJECT
var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
// (B) FILE HANDLER & FILE STREAM
const fileHandle = await window.showSaveFilePicker({
types: [{
description: "Text file",
accept: {"text/plain": [".txt"]}
}]
});
const fileStream = await fileHandle.createWritable();
// (C) WRITE FILE
await fileStream.write(myBlob);
await fileStream.close();
}
</script>
<input type="button" value="Save File" onclick="saveFile()"/>
// (A) LOAD FILE SYSTEM MODULE
// https://nodejs.org/api/fs.html
const fs = require("fs");
// (B) WRITE TO FILE
fs.writeFile("demo.txt", "CONTENT", "utf8", (error, data) => {
console.log("Write complete");
console.log(error);
console.log(data);
});
/* (C) READ FROM FILE
fs.readFile("demo.txt", "utf8", (error, data) => {
console.log("Read complete");
console.log(error);
console.log(data);
});
*/
It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.
While most despise Flash, it is a viable option for providing "save" and "save as" functionality in your html/javascript environment.
I've created a widget called "OpenSave" that provides this functionality available here:
http://www.gieson.com/Library/projects/utilities/opensave/
-mike
So, your real question is: "How can JavaScript save to a local file?"
Take a look at http://www.tiddlywiki.com/
They save their HTML page locally after you have "changed" it internally.
[ UPDATE 2016.01.31 ]
TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.
TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(
[ END OF UPDATE
The trick is, you have to open the page as file:// not as http:// to be able to save locally.
The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.
-Jesse
If you are using FireFox you can use the File HandleAPI
https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API
I had just tested it out and it works!