The HTML and JavaScript code below makes use of some features of HTML5 (specifically the “Blob” object, the File API, and the “download” attribute of the “a” tag) to allow the user to load, edit, and save a text file on their local computer. As of this writing, it works in both Chrome and Firefox browsers, though sadly it requires a little bit of custom code for each.
To see it in action, copy it into an .html file and open that file in a web browser that runs JavaScript. Or, for an online version, visit http://thiscouldbebetter.neocities.org/texteditor.html.
UPDATE 2016/06/13 – I have updated this code to reflect the fact that the window.URL object is no longer experimental, and thus is not invoked using different names in different browsers. The code is a little cleaner as a result.
<html> <body> <table> <tr><td>Text to Save:</td></tr> <tr> <td colspan="3"> <textarea id="inputTextToSave" cols="80" rows="25"></textarea> </td> </tr> <tr> <td>Filename to Save As:</td> <td><input id="inputFileNameToSaveAs"></input></td> <td><button onclick="saveTextAsFile()">Save Text to File</button></td> </tr> <tr> <td>Select a File to Load:</td> <td><input type="file" id="fileToLoad"></td> <td><button onclick="loadFileAsText()">Load Selected File</button><td> </tr> </table> <script type="text/javascript"> function saveTextAsFile() { var textToSave = document.getElementById("inputTextToSave").value; var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"}); var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob); var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; downloadLink.href = textToSaveAsURL; downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); downloadLink.click(); } function destroyClickedElement(event) { document.body.removeChild(event.target); } function loadFileAsText() { var fileToLoad = document.getElementById("fileToLoad").files[0]; var fileReader = new FileReader(); fileReader.onload = function(fileLoadedEvent) { var textFromFileLoaded = fileLoadedEvent.target.result; document.getElementById("inputTextToSave").value = textFromFileLoaded; }; fileReader.readAsText(fileToLoad, "UTF-8"); } </script> </body> </html>
This script is just what i have been looking for, thanks a lot.
And as written there: This Could Be Better,
i am now working on it.
Regards,
Hadi.
Thank you very much for this script…
Thanks, very simple solution…
The saving file function is not working, need help
The “download” attribute of the “a” tab only seems to work on the Google Chrome browser. Since “download” wasn’t supported on other browsers, when I originally wrote this script I didn’t even bother to make sure it worked on other browsers. I’ve just updated it so that the save code actually gets executed in Firefox, but it still doesn’t work, because Firefox still doesn’t seem to support the download attribute. Sorry for the inconvenience.
Yes sir I’ve used firefox browser thanks a lot
Actually, now that I’ve looked at it some more, it appears that Firefox actually is supporting the download attribute now. It’s hard for me to figure out from their bug tracker when exactly this happened, but it’s possible that it was just last week. In any event, what was actually causing my recent update to fail on Firefox was that calling “.click()” on my “a” link wasn’t doing anything. I have added a workaround in the code for Firefox that will append the download link to the DOM after the Save button is clicked. If the user then manually clicks the link, the download will proceed, and the link will be removed. Repeat as necessary. It’s not perfect, but maybe it will help…
this is a fantastic. just one thing I i am truing to change the output position of the download link. I would like it to appear by a button but its forming at the bottom of the page is there anyway to change this ?
Sure. Try setting the “id” attribute on the element you want to insert it before to “elementToInsertBefore”, then replace the call to “document.body.appendChild(downloadLink)” with something like:
document.body.insertBefore(document.getElementById(“elementToInsertBefore”), downloadLink);
Irritatingly, there is no “insertAfter()” method, but according to the Internet, there’s ways to fake it.
Sigh… actually, it looks like the arguments in that call to “insertBefore” in my previous comment are reversed. Sorry about that.
Absolutely awesome. Thx for this… With a bit of correction it validates strict, too ,-)
Helped a lot to improve my clientside SourceCodeComposer. Nice piece of JavaScript.
Hopefully it will be supported by Opera and Safari soon… Cheers, Guerteltier (Pango)
sir i need a code using javascript by clicking the menu open window want to display and by clicking the open the contents in the file want to display in text area …….. plss help me sirr.. its urgent .
pls anyone help me…… for cut copy paste inside textarea using javascript by clicking on the link
Thank you…
This is exactly what I was looking for!! 🙂
hi mira
First off thanks for this post… really awesome! Can anyone identify exactly what I have to change so I can use the download feature for a phone? Works on home computer, but it fails to grab the title and it also downloads the html instead of text.
I will keep looking around for a fix.
Major minor victory. I have discovered: for whatever reason when you download the file and try to use the phone native app to views the file, which is unfortunately in my case a code editor. By the way I am using my optimus G as my testing environment. It just shows the code and not the files contents nor the file name. But, if you use the dropbox editor it will show your note and the file name. I don’t know why dropbox will view the saved file the way it is supposed to be viewed and the androids stock file editor shows the back end code.
Still trying to find an alternative that doesn’t rely on a text editor to view the file, but thought I would mention it. You can at least us the file now whereas before you couldn’t. So, yay!
I have been testing out a php solution, which is thus far working perfectly. When I perfect it I plan on sharing.
My linter is telling me I’m an idiot for not closing my button tag, which makes me ask. Why do you open a “button” and close it as an “anchor”? Seems logical that this should not work.
Well, it USED to be an anchor, if it makes you feel any better. I’ll fix this when I get a moment. Thanks for your conscientious linting. You’re a better person than I am.
Firefox hack for auto click:
function saveTextAsFile() {
var textToWrite = document.getElementById(“inputTextToSave”).value,
textFileAsBlob = new Blob(
[textToWrite],
{ type : ‘text/plain’ }
),
fileNameToSaveAs= document.getElementById(‘inputFileNameToSaveAs’).value,
downloadLink = document.createElement(“a”);
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = ‘Download File’;
if ( window.webkitURL != null ) {
// Chrome allows the link to be clicked programmatically.
downloadLink.href = window.webkitURL.createObjectURL( textFileAsBlob );
downloadLink.click();
} else {
// Firefox requires the user to actually click the link.
downloadLink.href = window.URL.createObjectURL( textFileAsBlob );
// this hides it
downloadLink.style.display = ‘none’;
downloadLink.onclick = destroyClickedElement;
document.body.appendChild( downloadLink );
// now it can be auto clicked like in chrome
downloadLink.click();
}
}
Thanks! I have incorporated your fix into the code and updated this post accordingly. I appreciate the help.
Can you please help me to write a code such that it should save the text in my local file instead of downloading
this is my coding. after saving my file the blank space and new lines are filled with (null) character .. while running in java compiler pls.. help me. how to solve this problem
function SaveVarAsFile(te)
{
SaveFrame.document.open(“text”,”write”)
SaveFrame.document.write() ;
var s=document.forms[‘te’].elements[‘T’].value;
SaveFrame.document.write(s);
SaveFrame.document.close();
SaveFrame.focus(te)
SaveFrame.document.execCommand(‘SaveAs’,true,’shape.txt’);
}
  Save
Hi, i´m needing so much your help. I used your code and i thought it amazing and perfect. I´m needing your help to solve a doubt:
How can i save directly to a specific file? For example, i don´t want the textfield where the person puts the name of the file, i want that when he finish to write a text, he save in a defined(by me) directory and file, instead of he choose where he wants to save.
Pls help me with this, i´m needing your help.
Since now thanks
While it would probably be easy, even trivial, to set the filename from code rather than from the text box, I’m pretty sure there’s no way to save the file directly to the user’s filesystem without going through the download dialog. That’s intentional, because it prevents people from just installing random viruses on your computer when you visit a webpage. Sorry!
Just found this page, as it is a problem I have long looked for answers to. I entered a path/filename, but the file saved to W10 Downloads.
To answer the point above, why not create a function containing the filename, and have a click box to add it to the filename textarea?
I want to keep a lot of simple data in TXT files, and have instant access to them to make changes.
I break my information down into very small ‘chunks’, so I never have to wade through loads of stuff to find what I want to alter.
These files are then assembled by a script into an HTML page.
I hate having to click through Windows Explorer to find files.
The whole POINT OF COMPUTING, is to prevent having to re-invent the wheel, when one piece of code does it for you.
Excellent
1
Hi sir,
Actually i am try to little bit more. i am trying to read the text file and display in table form. but i am facing problem that i can’t edit the text in the file using your this script. so what should i do for edit the the files.
thanks if you can help.just let me know how this script allow to do modification.
means what i am doing that. i am scanning roll no name and marks from html page and try to insert it in my text file. but using this script it is replacing my older text.
if you can help.
Thanks for such a good help. Could you please tell how can we run it on safari(mac)?
Hi. I’m quite newbie with js and I can’t understand, how I’ll do the following.
I have made few small games and I want to save hiscores to .txt file locally.
I can’t get this great example working with paths like c:\temp. How can I change reading / writing path? Now it saves to downloads-folder. And when I try to read, I can’t set path in code to downloads folder.
Thanks. Lots of thanks. I wasted so much time reading other convoluted, poorly explained and badly coded examples that ended up not working anyway. This was the one piece missing from the javascript puzzle.
And also remember to call URL.revokeObjectURL()
i dont understand where ur using browse button in html and no event for browse button in javascript
Well, technically, the “Browse” button isn’t really a button. Yeah, I can see how that might be a bit confusing. It’s part of the input named “fileToLoad”, because its type is “file”:
<input type=”file” id=”fileToLoad”>
When you click it, the browser itself handles that event, not any JavaScript that I’ve written.
what does these lines represent
1. document.createElement(“a”); what is this does it create a anchor tag??
2.document.getElementById(“fileToLoad”).files[0]; what is tat files[0]????
3.fileReader.readAsText(fileToLoad, “UTF-8”);
1. Yes, it creates an anchor tag.
2. When you click the Browse button and choose a file, it goes in the “files” array of the “fileToLoad” input element.
3. This instructs the fileReader object to load the contents of the file as text in the UTF-8 format.
ok i tried to do like this .document.getElementById(“fileToLoad”).files[1]; its not inserting anything?will it load only in Zero th index???
Yes, presumably the files[1] would only be available if you somehow selected two or more files in the file picker dialog that appears when you click Browse. There may be some setting you can set on that input to allow you to select multiple files, or maybe you can just Ctrl-click multiple files or something. I’m not sure.
I love this! Thanks Alots! 😀
instead of user selecting the file, i want to directly pick a file which is in the same folder as my html and display its content, how to do that, pls help.
Hi San. Although thousands want universal browser read privileges to return (what you describe), it has been eliminated due to security concerns. Maybe someday, a localFile web page (file:///somepage.htm) will be able to read another localfile IF it is from the same domain/baseURL… without needing to select it with a filePicker. I hope. So do you. Keep your fingers crossed. 🙂
“TypeError: window.URL.createObjectURL is not a function”
I got this error with Firefox, but it is working smoothly in Chrome, pls let me know what is the reason I am getting this above error as soon as possible.
I use your code to save a html file (change type text/plain to text/html and use .html extension), when I try to open locally with internet explorer styles files don’t load (local style css file) this hapens just with explorer, with other browser like chrome is ok. If I open the saved html file in an editor and save’s (not change anything) and open again with explorer work ok, I thing there is a problem with the api file to blob the code in html type, maybe is malformed o currupted. If you o someone know how to fix this problem y apreciated to mucho if is shared, thank. (English is not my language sorry by the mistakes)
Fantastic… thanks so much.
I have used/modified your code… I throw a popup window to the user to provide a filename to read (or write), then pass the results back to my read/write routines. When they provide a filename (or select from the “file” dialogue), I tell it to close the window. This works great.
The only issue I had was (using Firefox) I had to remove the “destroyclickedElement” command or it would not work.
Epic, many thanks for that!
Hi everybody, i release the code only allow us to save 1 data into a text file. if i want to save multiple data, how do i code it?
Thank you so much! I have been searching for hours and your code works beautifully
Hi
Thanks for this wonderful code. Can it be customised to work on safari(mac) as well?
Thanks
How can I give it a path to where the file will go?
I don’t think you can. That would require the program to have knowledge of the user’s filesystem, which is probably a security no-no for the browser. I could be wrong, though.
This input statement that fetches the file before it is read is causing me a problem. I can write the file fine, but I do not seem to be able to get the name of the file =”fileToLoad” from the input function to my read the data function. Is there any way to invoke this input function from inside javascript so I can just create a global variable that the input function can share with the read function? In other words can this be written as a javascript function that can be called? Thanks. The file it writes is wunderbar.
Thanks for any suggestions.
can we specify the path in here, when I click save button, it download the file in download folder.
I want to change the path
thank for the code. how to set the downloaded file path so that i can easily know? thank you in advance..
Searching for the same thing…did you get an answer?
How to save this file onto a particular directory?
This has been a popular question lately. I’ve tried to respond no fewer than two times, but for some reason my response keeps getting eaten by the comment system.
At any rate, I don’t know any way to specify a particular directory to save your file. I tried to get that working when I first wrote this program, but I was never able to figure anything out. My feeling is that leaving this functionality out is probably a security feature, since otherwise they’d have to give the browser knowledge of the user’s filesystem, which may be considered a no-no. But that’s what they always used to say about allowing web pages to save files to the local system in the first place, so who knows.
Anyway, if you do figure this out, please let me know how…
Hi
Just copy and pasted your code it’s working fine. Thanks for the code. I was looking something like this. Basically am a designer, just have little bit of programming knowledge only. I want save user input on the same page rather creating a file and downloading it. Is it possible? Can you help me
Well, this is probably not what you really want, but it technically does what you requested. You’d probably be better off just learning to program, though.
<html>
<body>
<input id=”inputTextToSave” />
<button onclick=”saveText();”>Save</button>
<p id=”pTextSaved” />
<script type=’text/javascript’>
function saveText()
{
var inputTextToSave = document.getElementById(“inputTextToSave”);
var textToSave = inputTextToSave.value;
var pTextSaved = document.getElementById(“pTextSaved”);
pTextSaved.innerHTML = textToSave;
}
</script>
</body>
</html>
Hi This was very useful for me. It was working fine in Chrome and in IE i was getting access denied. When i google’d further i got this soultion. for IE you need to add few lines of code in between, please find the modified function below which works on IE, Chrome & Firefox. Hope somebody finds it useful.
function saveTextAsFile()
{
var textToWrite = document.getElementById(“inputTextToSave”).value;
var textFileAsBlob = new Blob([textToWrite], {type:’text/plain’});
var fileNameToSaveAs = document.getElementById(“inputFileNameToSaveAs”).value;
var browserName=navigator.appName;
if (browserName==”Microsoft Internet Explorer”)
{
window.navigator.msSaveBlob(textFileAsBlob, fileNameToSaveAs );
}
else
{
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();
}
}
The URL for IE Blob is http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Vignesh you little beauty….
Thanks a lot for the solution in IE…
1..After Editing how to override the browse file with same path in our PC.
2..Can you change this code to typescript.
Advanced thanks
Hi there, thank you very much for such a wonderful code. I just want to ask you a question, is there a way to change the “document.getElementByid” to “document.getElementByClassName”. The reason I want to do that is because I want to add other textareas and save all of them in one file. Thanks in advance 🙂
That doesn’t sound too hard. You might be able to just replace the first line of saveTextAsFile() with something like this:
var textToWrite = “”;
var inputsContainingTextToSave = document.getElementByClassName(“GeorgesTextareaClass”);
for (var i = 0; i < textareasToSave.length; i++)
{
var textarea = textareasToSave[i];
textToWrite += textarea.value; // .innerHTML?
}
Something like that, anyway.
when you save the file it loses the basic formatting of line breaks. The text will then save if a line break has been added without any space at all. Anyone know how to fix this?
The line breaks are still there, but they’re Unix-formatted rather than Windows-formatted. Unix uses just the “linefeed” control character to encode line breaks, which is commonly encoded as “\n”. Windows, on the other hand, uses a carriage return AND a line feed to encode line breaks, which is represented like this: “\r\n”. So in order to save the file with Windows-style line breaks, you’ll need to add something like:
textToWrite = textToWrite.replace(“\n”, “\r\n”);
Alternately, you could open the saved text file with a program that understands Linux-style line breaks, like Notepad++.
I am trying to have multiple text boxes that i can save. As it is using document.getElementById it will save only the first one. When changing to document.getElementByClassName it doesn’t work
how can I do it so I have more than one on a page?
thanks
This is kind of Programming 101, but since getElementsByClassName() returns an array (list) of values rather than a single one, you’ll need to loop through each value in the array and perform whatever operation you want to do on each of them. Like:
var elements = document.getElementsByClassName(“someClassName”);
for (var i = 0; i < elements.length; i++)
{
var element = elements[i];
// do something with the element
}
Or, now that I look at it, you might just go look at my response to George a few comments back, on 04/21. I completely forgot I wrote that.
Hi
Firstly thanks a lot for a wonderful solution.Worked like charm for my current application’s requirements.!!
I would in addition to the text being saved as .txt file needs to save it as PDF too. Would really appreciate, if you can guide me for the same.
Thanks
Keshav
Thanks for the article! However, there’s something I don’t understand: why isn’t “reader” or “this” used instead of “fileLoadedEvent.target” while they all refer to the “FileReader” object: http://jsfiddle.net/Mori/tJBHZ/
Awesome! Thank you…
I was looking for such a simple solution and you did it!
Cheers
Pascal
Any way for save textarea file upload into dropbox api?
()
Hi Sir, I have added learned a lot from this blog and this was very much help full in learning to make a bookmarklet. thanks.
Which is the license for code of the functions?
There’s no license. You can use it as you like.
There’s nothing particularly clever or novel about this code, I’m just demonstrating some of the bare functionality of HTML5 in the simplest way I can. I don’t believe in software patents, and I consider this too simple and generic to even be copyrightable. Have fun.
Hi there,
Can you please help me find solution for dynamically creating a html file, consisted from textarea value, and pass it as source to an iframe
hello guys, help me for this script…
how i can save as .txt file
I was try this script is working, not .txt file but windows file.
For button is:
tsk tsk tsk!, thats why i love html5, thanks a lot for this code, , cool men, , it helps a lot. 😀
The Code is fantastic, no doubt.
But I am facing one problem when I insert multiline string in the text area and save it.. It generates the text file with no line break. May be the blob is not saving newline in the file..
so is there any way to save it the way we want.
For Eg: if text area contains the following.
“Hello Everyone
This is JavaScript”
Then it generates the resulted file containing text like:
“Hello EveryoneThis is JavaScript”
Please help if anyone can….
It’s been a long time since I’ve looked at this code, but I think probably what’s happening is that the text is being saved using just a linefeed as the line break character, which is how they do it in Unix, rather than with a carriage return character AND a linefeed character, which is what Windows is expecting. Try downloading Notepad++ and opening the file there, and see if it looks right. To fix the problem for Windows, you’d probably use something like “textToSave.split(“\n”).join(“\r\n”) to replace the linefeeds with carriage return/linefeed pairs.
Hi,
This code work perfect in Chrome and firefox. I want this same implementation for IE 9+ browser also. is it possible ?
Sorry,I have just one question,and please for answer,because I just need that solution.How to add an option which adds the text in the already exciting .txt file?
It sounds like you want to do that automatically, without the user having to mess with the Save dialog. If so, I don’t think that’s currently possible. All you can do is load the file, add to the end of it, click Save, and then choose to overwrite the same file in the dialog. Sorry!
No,Save dialog is totally ok,I just need to text be saved to same file.But,what happend-when I want to overwrite the same file,that is impossible,because computer automatically made same .txt file with extension of (1),or (2)..
For example:I have test.txt,when I load it,write something at the end,and click save,he made test(1).txt..
Is there any solution?
Hi,
Thank you for posting this code. It really helps me. Now, My requirement is The text file will automatically save into the drive,without asking file name and location to save.
If it possible please solve this issue.
Thank You…!!
No, I don’t believe this is possible, as such functionality is widely considered a security risk. Maybe someday web browser developers will decide on some compromise to make this feasible, but I wouldn’t hold my breath. Sorry.
Wow an awsome codes that helped me in projects
I want to use just the upload part of the code, as I already have a save function that saves the txt as a word doc. Using the code as it is currently breaks my system.
Put your code in a gist at GitHub.
Are you using Internet Explorer? Because this code doesn’t work in my current version of IE. But it works in my versions of Chrome and Firefox, which I believe are more-or-less up to date.
No, I’m using Chrome and FF.
Superb code. I’ve been looking for something like this for two weeks. I have a program that outlines and manipulates text and then codes the text into javascript variables and saves the file locally with a .js extension. Then I edit that file in a different program using your code to open the .js file, read the js variables, and save the outside file to the inside file (the one inside the directory where the editor is located) so that in the editor program can read each of the variables. Works beautifully offline (as long as I remember to refresh the browser). My question is about what happens when I put the editor online.
If I have five or six students using the editor simultaneously (each one of them rewriting the current.js variable file on the server), what happens (if anything) to their variable text? I assume their text remains theirs for the rest of the browser session, but what happens on the server if two or three people rewrite the current.js file simultaneously and wait too long to refresh the browser (I’ve included a refresh button below your code)? Will they load a different person’s variables?
I’d love to bypass the altogether and just read the variables from the external file without having to save it on the server, but for the life of me I have no idea how to do it. Sorry for being so long winded. Any suggestions would be appreciated.
And again, thanks for the elegant code.
Not sure whether this is what you need, but you can use the eval() function to execute the contents of a string as JavaScript. For example:
var thingToSay = “If you’re seeing this, it worked!”;
var functionAsString =
“function saySomething(whatToSay)”
+ “{”
+ ” alert(whatToSay);”
+ “}”;
eval(functionAsString);
saySomething(thingToSay);
it helps me thanks alot man!!
After days searching the Internet – Eureka!! I found your solution.
It works!! and it does ‘what it says on the tin’. Many thanks.
Hi, Interesting I want to set a fixed txt file and display its content too. I read above that it’s not possible due to security reasons. Is there anyway to get using a library like JSON or something like that? Thanks
Thanks for such a woderful code But each time when we execute the code it will create copy of file how to overwrite file at each time of execution
i want the code to modify and save to the same text file
Pingback: Como manter indentação e quebras de linha ao salvar um arquivo texto via javascript | DL-UAT
Thanks,
It’s works.
thanks and the code works better…
Can anyone temme, how to process the text file that gets download with java and to show the result again in webpage??
@Hello sir,, thanks alot for posting this. this is what exactly am searching..!!! but i need this code with some slight modification. i want to upload an image file and save it in local machine… could you pls help. well let me explain clearly..!!!!
-i want to upload an image file using button. i did it sir. but it only shows the file name next to the button only.
-Now i want to save the uploaded file in my”c:\” location with separate folder – named as “uploaded image files” after clicking submit button with “your file uploaded successfully” message.
then i want to store the same data in server database as well.
. finally, i need to download that same file from server database.
hope you understand and help me to accomplish my university project sir,
Hi All,
I have a requirement like i have to save the browse selected file to downloads with the same file type extension (example a .apk or .ipa files should be downloaded as same file type)
Hi,
You could use the following syntax:
See also http://www.w3schools.com/tags/att_input_accept.asp
Cheers
Solution has been removed during the process.
Use the ‘accept’ attribute in the input tag
i.e. input type=”file” id=”fileToLoad” accept=”.apk”
Reblogged this on In My Words.
Fantastic … Exactly what I wanted … Thank you …
Why is this code not saving line breaks and indentations? Do we have any solutions to that? Thanks again.
I don’t know about indentations… maybe pressing tab is simply moving focus to the next control, rather than inserting a tab character? But as for line breaks, it IS saving them. It’s just saving them as Unix-style line breaks, rather than Windows-style ones. See previous comments for details.
Thanks . This was very helpful and exactly what I needed
Thanks!
Could this be used to save data input from a simple HTML form that I created?
I created a form that I want to save the data from as a txt document would the above posted code be used for this or is that not possible?
Thank you for your code example 😀 Its exactly the kind of simple file save/loading I wanted.
Your whole site is a treasure trove of good example code, much appreciated!
Simply great
Pingback: Saving text in a local file in Internet Explorer 10 - BlogoSfera
Pingback: rotatengine.js | bthj
hello,
This is really cool, but can you help me and tell me how to apply it for multiple inputs? which i guess will use CLASS instead of ID, but when ever i use “getFileByClassName()” in this script it saves me a file named “undefined” and with the word “undefined” inside the text file.. so how can I save all (more then a 100) text field using this script. And is it even possible?
Well, for starters, I don’t think there is a JavaScript function named “getFileByClassName()”. Maybe you want to try “getElementsByClassName()” instead? After you have all the the fields, you’ll probably just loop through them and concatenate each to the end of a string, then save that to a file.
um yeah I’m sorry, I meant “getElementByClassName()”……ahaa okay can you please provide more help? with my 3weeks experience of Javascript I don’t believe that i fully understand how to do what you said! although to mention I know the “for” and “while” loops… but can you provide more? and sorry for any inconvenience sir. but I really need it and it would be appreciated..
Okay, so it’s really hard to give HTML code examples in these comments, because WordPress handles them out unpredictably. But basically, replace the single textarea element from the code in the article with a bunch of inputs that all have the same class, for example, “inputTextToSave”. Then replace the first line of the saveTextAsFile() function with these lines:
var textToWrite = “”;
var inputsTextToSave = document.getElementsByClassName(“inputTextToSave”);
for (var i = 0; i < inputsTextToSave.length; i++)
{
var inputTextToSave = inputsTextToSave[i];
var textFromInput = inputTextToSave.value;
textToWrite += textFromInput;
}
Incidentally, if you’re a beginning programmer, I did post a .pdf booklet last year that teaches the rudiments of programming JavaScript, at least the way I do it. I realize nobody reads books to learn coding anymore, but if you’re interested anyway, see https://thiscouldbebetter.wordpress.com/2014/12/12/a-guide-to-programming-for-the-beginner.
Message from the future!
I cant seem to manage to make it work for multiple inputs data.
i do everything as you suggest,but i still get an [HTML object collection] within the .txt,in addition to this,when i load it back its not bringing back anything to the textarea.
Man if you ever return from the past,nice to have you back,could you dedicate a couple of minutes to a complete stranger and make a working version for more than 1 input?
The world may return this favour to you with vast richness and greatness !
Thanks a lot.. but it didn’t work.. when ever I press the “save text to file”.. nothing happens.. what do you think ?
Thanks a lot for the pdf tho, it seems really help full.
Thanks a lot. You killed it man 😀
When i give save it should ask where to save to user instead of saving automatically how its possible..
If the file is being saved without asking where you want it, it’s likely because your browser is set up to just automatically download everything to your specified downloads folder. So if you want to choose the save location, you’ll probably need to change your browser’s settings. As far as I know, there’s no way to override that behavior with HTML5 or JavaScript. Sorry.
How to make it such that I should ask where to save instead of auto saving…
Please some one help!!!…What should i modify in the code so that instead of .txt file,.zip file can be uploaded and downloaded locally….
Instead of .txt file, can I use .zip file….If so please can you give me the modifications of the above code…
As far as I know, there’s no really simple way to change this code to save a ZIP file. You might want to check out JSZip, which is a JavaScript library for working with ZIP files. I make use of this library in this post. That code only reads from a .ZIP file, rather than creating one, but I think JSZip supports creating ZIP files as well.
Thank you so much! I’ve been looking for this–trying to replace an ActiveX FSO because Edge doesn’t do ActiveX (neither does FF or Chrome or Safari or Opera). Two weeks of searching, and your code just works!
Hi ,
My requirement – Had a “test.txt” text file in local directory.
Also had a button “Save” in HTML . When clicked it , some text need to be append to the “test.txt” file. Can we achieve this using Javascript.
Note- I am fetching the file path and filename before click.
Thanks in advance . Let me know if anyone can help me.
Krishna.
No, as far as I know you cannot automatically write to a file on your local filesystem without going through some sort of dialog. Sorry.
Thank you. I have started to work on an xml converter, and almost found no way to save the converted file on the local HDD.
Everything is fine. But it is not working for Unicode text, for example : Unicode based Hindi Language text is not displaying properly.
Pingback: TF / Modulos: guardar archivo – almendro
Hello Sir,
This code really very helpful for us but sir I cant save my image , please will you give the solution.
Thank you.
I’m not quite sure exactly what you’re asking, but if you want to load, edit and save images you might take a look at one of my other posts, which includes the code for a simple image-editing program: https://thiscouldbebetter.wordpress.com/2013/01/19/a-simple-paint-program-in-javascript-using-html5.
Hey,
Like a bunch of others here, I want to save some text to an existing file that would server as a simple, local ‘database’. So instead of creating and downloading a new file, edit an existing one.
I’ve read all your answers to the other questions, and you mention that it’s not possible due to security reasons.
However, according to various sources, it should be (at least now, anno 2016) possible under certain conditions. From what I’ve read it’s possible if:
– you use a ‘blob’;
– Chrome is used, opened with –allow-file-access-from-files as a parameter.
Since this post is from 2012, and the most recent comment is from 2014, I’d figure things may have changed by now, and perhaps also your knowledge about this. You seem to have a good know-how about this stuff, so would you mind giving it another look? (You’d make me very happy 🙂 )
Cheers
Thank you so much. This is exactly what I was looking for. I wanted to use this method to save (export) the Data of an AnuglarJS form into local text file (json format), and allow the user later to import the file. I am sure that this approach will work.
I am very new to HTML and all web technologies… This content gave a shape to my thoughts. Now I can achieve my logic with this. Thanks A lot…
Do not ask me what was my thought to implement.. 🙂 😛 😀
Hello, I want to fetch contents of text file and store it to variable of javascript and I tried the following code, by using iframe in html and store it in one variable for login purpose. When I login first time in all browser its work perfect but, after login first time the issue is when I update the files i.e. username.txt and password.txt then the all browsers shows alert of error message of “username or password is wrong” I noticed that all browsers stores older value, its not update latest changed value from files. I tried all methods like removing cache. Plz can any one help me.
when i refresh firefox,IE it works but chrome needs 20-30 refresh.
YouFi Router
Welcome to Internet Service
Username :
Password :
http://username.txt
http://password.txt
function check(form)/*function to check userid & password*/
{
var id=document.getElementById(‘username’).contentDocument.body.firstChild.innerHTML;
var pass=document.getElementById(‘password’).contentDocument.body.firstChild.innerHTML;
window.location.replace(“index.html”);
if(form.userid.value == id && form.pswrd.value == pass)
{
window.location.replace(“index.html”);
window.open(‘/cgi-bin/shell’,’_self’);
}
else
{
location.reload(true);
window.location.replace(“index.html”);
alert(“Error Username or Password is wrong”);
}
}
Thank You,
Vishal.
can you please tell me the code for saving form data to a text file using javascript
I used shell script to store data in txt file.@palak
Hero of the day, Thanks
I am probably missing the obvious but.. how do you modify this code to work as a bookmarklet that I can put in the browser toolbar and then, whenever I visit a webpage… I select some text, click on the bookmarklet button, and I get a dialog window that lets me save that selected text into a local file? Thanks!
Hi Thiscouldbebaetter,
Awesome script, thank you very much.
I’m hoping you can help me if it’s not too much to ask.
I have a form with several checkboxes in it.
What I’m trying to do is for each checkbox ticked I’d like to send the value to a text file.
Is this possible?
Sure, it should be easy. It’s a little difficult to put HTML in a WordPress comment, though, so bear with me.
If your checkbox is declared like this: “[input id=”checkboxYesOrNo” type=”checkbox”][/input]” (with angle brackets rather than square brackets), then you can get its value in the JavaScript with “var yesOrNo = document.getElementById(‘checkboxYesOrNo’).checked;” Then you can use that value to build a string, and save the string to file with the script from this post. Good luck!
That works great thank you.
I have one more problem if you don’t mind helping (I’m not too good with javascript yet. Still learning). I want to use this script to make a playlist file.
The problem I’m having is the link is formatted as [track][location]path to file[/location][/track]
I can’t get the [/track] to show up.
Sorry the problem is with code I’ve added. Yours works fine
Reblogged this on COFFEE | PAPER.
Thank you very much
Got this working great now, thank you. Is there any way to clear the text area after the file has been written? Automatically would be great, but a button would be ok too.
just put a line before document.body.removeChild(event.target);
document.getElementById(“inputTextToSave”).value = ”;
This is a great code a piece of cake script..thank you very much..very helpful..
it’s really superb
but can i load edit and save the same file instead of downloading the separate file every time, please give me the code for this, if possible 🙂
If you want to save to the same file, you can manually select that file in the dialog. There’s still no way to do it automatically that I know of.
Manually selecting
a file you use frequently
renders useless
the whole point of computing.
Surely
the function of computing
is to save time
by never needing to reinvent the wheel
each time you want to make a journey?
The best solution I have yet found
is in Notepad++
( settings / preferences / MISC / Clickable link settings / Enable ),
where one can use links within a .TXT
to open text and HTML files.
One can also open folders in Windows Explorer
from within a .TXT file.
This function with WE
removes the necessity
to go to the drive root,
and up to the folder you want,
replacing it with one click.
🙂 Zen
Great! Could you please improve it to be able to load file by drag and drop a file over textarea ?
And one question – do you know why this code is not working on JSFiddle ? https://jsfiddle.net/u73vr17f/2/
It doesn’t seem to work in IE.
hii,
thanks for the code. Can you please help me to load more than one files, I can select multiple files right now but I couldn’t load. I request you to help over this as soon as possible since i am new to this coding.:-)
i need a help, i need to upload a file and download it to any folder in hard disk, i wish to use this between different computers
hi,
i have one doubt when i load some file into textarea it shows the content and if i make any changes in that i getting updated file at time of clicking the save button that was fine. but actually what i want here what i changed in that file the same thing will happen in source file(where i loaded that file i.e. local file) but i need to use only javascript don’t depend on any server side scripting whether it possible to do…..
This is great piece of code. How can I make it work in IE. Click on the save to file doesn’t seems to do anything
you’re welcome
Uh… thanks? : )
This is great solution!
Because I want to incorporate the code in a page of my web site, I would wish you to tell to me some way in order to change the CSS of the table.
Probably the question seems stupid.
Just tell to me where I must look to find the answer.
Thank you.
I suppose you might check out the CSS tutorial at “https://www.w3schools.com/css/”.
Thanks a lot. This was so helpful. Two things:
1. Can I just use this in a cordova android app or do I require something more
2. Rather than download to default download location, how do I let user select download location before going ahead to download (like the browser “Save As” effect)
How would you load a file automatically into the text box? Perfect piece of code extactly what I was looking for.
Many thanks
I’ve been trying to figure out how to keep the file popup from appearing. I’d like it to write ‘silently’. Thanks!
You can’t. It’s a security feature.
Hello ..This code works fine but what if i have multiple textboxes and i want to save multiple textboxes in a file like Id:1,Name:Kumar and when we load it has to store in proper textboxes how it is possible ???
Thank you very much for this great bit of code.
Several question have been asked. I’m happy to say that I found some answers.
The saved file line break is controlled by the endings option —
new Blob([textToSave], {type:”text/plain” , endings:”native”})
See: developer.mozilla.org/en-US/docs/Web/API/Blob/Blob & http://www.javascripture.com/Blob & developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
One can open multiple files by adding ‘multiple’ to the input box —
See: developer.mozilla.org/en-US/docs/Web/API/FileList
The list is a collection of file objects and can be accessed as — input.files[i].name Security apparently prevents their creation or change except by use of the ‘browse’ input.
I think this is the answer to my query below… My profeciency in javascript is not that good. how do you do this?
I’d like to save the text file with line breaks:
Example(this should appear in the saved text file):
Line 1
Line 2
AzA,
You need to do your homework. Look at the references and related pages. Experiment. Experiment. Experiment.
Note that security protocols prevent you from writing files with arbitrary names to your file system although you probably can re-write those you read. It is also possible to have an alternate file system known to the browser. Again, you gotta do your homework.
Also search for stuff and read the newsgroup <>
Thank you. This is very helpful as it is but how can it be done to make it save a txt file with space and wordwrap?
Example:
Line 1 text.
Line 2 text
Pingback: Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it? - QuestionFocus
Hi!
Awesome coding!
How can it be used to create not 1 but multiple .txt files?
Thanks!
mr.avik
Thanks for this post…I have one query….Can we open a specific file instead of browsing a file
Thanks for the code thiscouldbebetter , very helpful and I’ve found some excellent answers.
Only one doubt, It’s possible to change the extension for the download from .txt to any other, for example .xml? How can I do that?
Thank you in advance!
Got it
var textToSaveAsBlob = new Blob([textToSave], {type:”text/xml”});
Thanks for this. It is working really great but just a few questions here, when the file is saved, the formatting is gone. Like how the data is entered, that’s not how it’s showing on the saved file. Can you please help and teach me? Thanks
Pingback: html - возможно ли записать данные в файл, используя только JavaScript? - Переполнение стека
I don’t know Russian, but I ran this comment through Google Translate, and it seems to be a genuine comment, so I’m approving it.
Pingback: Is it possible to write data to file using only JavaScript? – inneka.com
I think this is amazing – given that there are lots of places with incorrect advice.
The only problem I’m having is I want to wait until the file is written and then do some screen updates. The updates get done too early and testing destroyClickedElement() shows that is called before the “save as” window appears. Any ideas?
As with almost everybody else, this codes is just what i was looking for – thanks!
For reading a file “loadFileAsText()” I would like to specify which file in the dialog box (which works great); however, then I’d like the selected file to be read automatically, without having to click another “Read File” button. If that’s not possible, then I’m happy with how it currently works.
Is it possible to save and load checkbox and radio values using this?
Sorry, I saw what you replied to someone else up above regarding this same question. Would it be possible to make a working example with this textbox example? Perhaps like having a checkbox and radio button in the form that gets saved and loaded back? That would be super helpful to see how it works!
Pingback: Save data from multiple inputs from html webpage as .txt (locally) and load them back at the same places – Ask Javascript Questions
Pingback: 无需Cookie或本地存储的用户识别|php问答
Pingback: 是否可以仅使用JavaScript将数据写入文件?_javascript问答
I Have To Save File Not to Download
Pingback: JavaScript 만 사용하여 파일에 데이터를 쓸 수 있습니까? abc.txt. 나는 - How IT
Is it possible to save the content from the body of a ckeditor, and open a file to load into the body?
I just get undefined. I need a way to write content as normal then save it as html with the tags
Thank you very much.
Pingback: How to save form data in div to a text file using HTML and Javascript – MVR
Pingback: How to save form data in div to a text file using HTML and Javascript – IMEDIO
Pingback: How to export source content within div to text/html file