Loading, Editing, and Saving a Text File in HTML5 Using Javascript

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.


	<tr><td>Text to Save:</td></tr>
		<td colspan="3">
			<textarea id="inputTextToSave" cols="80" rows="25"></textarea>
		<td>Filename to Save As:</td>
		<td><input id="inputFileNameToSaveAs"></input></td>
		<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
		<td>Select a File to Load:</td>
		<td><input type="file" id="fileToLoad"></td>
		<td><button onclick="loadFileAsText()">Load Selected File</button><td>

<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";


function destroyClickedElement(event)

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");



This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

142 Responses to Loading, Editing, and Saving a Text File in HTML5 Using Javascript

  1. Hadi says:

    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.


  2. Nithya says:

    Thank you very much for this script…

  3. YKY says:

    Thanks, very simple solution…

  4. Plyfo says:

    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.

      • Plyfo says:

        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…

  5. Legitkrillin says:

    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.

  6. Guerteltier says:

    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)

  7. sugan says:

    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 .

  8. sugan says:

    pls anyone help me…… for cut copy paste inside textarea using javascript by clicking on the link

  9. Mira says:

    Thank you…
    This is exactly what I was looking for!!🙂

  10. adolphin8pi says:

    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.

    • adolphin8pi says:

      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.

  11. adolphin8pi says:

    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.

  12. tip says:

    Firefox hack for auto click:

    function saveTextAsFile() {

    var textToWrite = document.getElementById(“inputTextToSave”).value,

    textFileAsBlob = new Blob(


    { 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 );


    } 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



  13. s says:

    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.write() ;
    var s=document.forms[‘te’].elements[‘T’].value;

    &nbsp Save


  14. André Santos says:

    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!

  15. Nishant says:


  16. Rajesh trivedi says:

    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.

    • Rajesh trivedi says:

      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.

  17. Dilip says:

    Thanks for such a good help. Could you please tell how can we run it on safari(mac)?

  18. JJ says:

    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.

  19. just some guy... ruler of the planet omicron persei 8! says:

    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.

  20. And also remember to call URL.revokeObjectURL()

  21. super says:

    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.

  22. super says:

    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.

      • super says:

        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.

  23. I love this! Thanks Alots!😀

  24. san says:

    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.

    • Larry Wendlandt says:

      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. 🙂

  25. Error in Firefox says:

    “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.

  26. Milton says:

    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)

  27. FCDobbs says:

    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.

  28. BigBang1112 says:

    Epic, many thanks for that!

  29. helloeverybody says:

    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?

  30. dromero says:

    Thank you so much! I have been searching for hours and your code works beautifully

  31. keshav says:

    Thanks for this wonderful code. Can it be customised to work on safari(mac) as well?


  32. Noel says:

    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.

  33. joe dart says:

    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.

  34. kori says:

    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

  35. ymtExpo says:

    thank for the code. how to set the downloaded file path so that i can easily know? thank you in advance..

  36. Yash says:

    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…

  37. Raghu says:

    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.


      <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;



  38. Vignesh says:

    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 );
    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);
    // 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”;


    The URL for IE Blob is http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx

  39. ram says:

    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

  40. George says:

    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.

  41. ted says:

    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++.

  42. ted says:

    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?

    • 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.

  43. gupkeskeshav says:

    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.


  44. Mori says:

    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/

  45. lovelyside says:

    Awesome! Thank you…

    I was looking for such a simple solution and you did it!


  46. noufalbinu says:

    Any way for save textarea file upload into dropbox api?

  47. 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.

  48. Alexandre Magno says:

    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.

  49. Kris says:

    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

  50. Summon Agus says:

    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.

    <script type='text/javascript'>
      function doDL(s){
        function dataUrl(data) {return "data:x-application/text," + 
          var d= document.open();
          d.execCommand( "saveAs", true,
        }//end IE?
      }//end doDL()

    For button is:

    <input value='Save' type='button' onclick='doDL(document.getElementById("t1").value)' />
  51. tsk tsk tsk!, thats why i love html5, thanks a lot for this code, , cool men, , it helps a lot.😀

  52. vishal says:

    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.

  53. Hariharan says:


    This code work perfect in Chrome and firefox. I want this same implementation for IE 9+ browser also. is it possible ?

  54. 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!

  55. 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?

  56. kumar says:

    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.

  57. Neon dragon says:

    Wow an awsome codes that helped me in projects

  58. Matt says:

    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.

  59. Matt says:

    No, I’m using Chrome and FF.

  60. Chas says:

    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);”
      + “}”;



  61. arun says:

    it helps me thanks alot man!!

  62. Bill Armitage says:

    After days searching the Internet – Eureka!! I found your solution.
    It works!! and it does ‘what it says on the tin’. Many thanks.

  63. Chema says:

    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

  64. 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

  65. kiranbr92@gmail.com says:

    i want the code to modify and save to the same text file

  66. Pingback: Como manter indentação e quebras de linha ao salvar um arquivo texto via javascript | DL-UAT

  67. yugo says:


    It’s works.

  68. Nihti says:

    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??

  69. Jaay says:

    @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,

  70. sampoori says:

    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)

  71. lovelyside says:

    Solution has been removed during the process.

    Use the ‘accept’ attribute in the input tag
    i.e. input type=”file” id=”fileToLoad” accept=”.apk”

  72. jsj14 says:

    Reblogged this on In My Words.

  73. Viswanadh says:

    Fantastic … Exactly what I wanted … Thank you …

  74. Luzan Baral says:

    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.

  75. Thanks . This was very helpful and exactly what I needed

  76. Sunny Kumar says:


  77. Harvey says:

    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?

  78. Alex says:

    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!

  79. kavitha says:

    Simply great

  80. Pingback: Saving text in a local file in Internet Explorer 10 - BlogoSfera

  81. Pingback: rotatengine.js | bthj

  82. khaled says:

    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.

      • khaled says:

        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.

  83. khaled says:

    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.

  84. KretaSei says:

    Thanks a lot. You killed it man😀

  85. 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.

  86. How to make it such that I should ask where to save instead of auto saving…

  87. Ankith says:

    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….

  88. Ankith says:

    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.

  89. 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!

  90. murali says:

    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.

  91. Peter says:

    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.

  92. Everything is fine. But it is not working for Unicode text, for example : Unicode based Hindi Language text is not displaying properly.

  93. Pingback: TF / Modulos: guardar archivo – almendro

  94. Aishwarya says:

    Hello Sir,

    This code really very helpful for us but sir I cant save my image , please will you give the solution.

    Thank you.

  95. Tjardo Krijt says:

    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🙂 )


  96. tarekahf says:

    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.

  97. Jaggu says:

    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..🙂😛😀

  98. Vishal Rabadiya says:

    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 :


    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;
    if(form.userid.value == id && form.pswrd.value == pass)
    alert(“Error Username or Password is wrong”);

    Thank You,

  99. palak mittal says:

    can you please tell me the code for saving form data to a text file using javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s