Skip to content Skip to sidebar Skip to footer

How To Save And Edit A File Using Javascript?

I want a user of my website to enter some text in a text area and when he submits the form, the text that he entered be stored in a .txt file that is present in same directory of t

Solution 1:

Yes you can, HTML5 File API has a saveAs API that can be used to save binary data using Javascript. You can generate a .txt file by first getting the data into a canvas and saving it as:

canvas.toBlob(function(blob) {
  saveAs(blob, filename);
});

See this demo, the text file is actually generated in browser without PHP. http://eligrey.com/demos/FileSaver.js/

There is an excellent article written back in 2011 by Eli Grey on html5rocks: http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side

More reading at W3C: Filesaver interface


Edit 2016 Update

My original answer showed an example using the BlobBuilder interface which has since been deprecated and marked as obsolete. It is now recommended to use the Blob Construct to manipulate binary data.

At the time of posting, Blob construct is supported on all major browsers. IE 11, Edge 13, Firefox 43, Chrome 45, Safari 9, Opera 35, iOS Safari 8.4, Android Chrome 49.

Demo:

More reading:

Solution 2:

You can't. You need some server-side script to access the filesystem of the server such as PHP or Java.

Solution 3:

This one might help you.

http://wcetdesigns.com/tutorials/2012/11/01/edit-save-file.htmlhttps://web.archive.org/web/20131210151034/http://wcetdesigns.com/tutorials/2012/11/01/edit-save-file.html

edit.php, file where users can edit using the textarea tag.
<html><head><scriptsrc="http://wcetdesigns.com/assets/javascript/jquery.js"></script><script>functionsave(){
     var x = $("textarea").val();
     var data = 'c='+x;

     $.ajax({
         type: 'POST',
         url: 'save.php',
         data: data,
         success: function(e){
             $("#s").html(e);
         }
     });
}
</script></head><body><textarea><?php$fn = "blank.html"; //FILE TO BE EDITED (FILENAME EDITABLE)$file = fopen($fn, "r+"); //OPENS IT$fr = fread($file, 1000000); //READS IT
fclose($file); //CLOSE CONNECTIONSecho$fr; //SHOWS THE EDITABLE FILE HERE?></textarea><br><inputonClick="save()"id="x"type="button"value="Save"><br><br><spanid="s"></span><br><ahref="blank.html"target="_new">view file</a></body></html>
save.php, file where the saving process will take place.
<?php$c = $_POST["c"]; //TEXT FROM THE FIELD$f = 'blank.html'; //FILE TO SAVE (FILENAME EDITABLE)$o = fopen($f, 'w+'); //OPENS IT$w = fwrite($o, $c); //SAVES FILES HERE$r = fread($o, 100000); //READS HERE
fclose($o); //CLOSES AFTER IT SAVES//DISPLAYS THE RESULTSif($w){
    echo'File saved';
} else {
    echo'Error saving file';
}

?>

Javascript doesn't have access to file system so you must use some server side language like PHP as in the given example

Solution 4:

you cant save file with js in server nor the client system. you need a server side script like php or asp.net to save files to server. but cant save anything other than a cookie to the client system.

Solution 5:

You can send that particular textarea value through ajax by javascript. Then on the server side you can put a code, where you can accept the string and save it in a text file. You cant just do it with Javascript, you need a serverside code..

//Html
    <textarea id="TextArea"></textarea>

    //javascriptvar dataVal = $('#TextArea').val();
    if(dataVal!="")
    {
    $.ajax({
                url: '/createTextFile',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: dataVal,
                success: function (response) {
                    alert('Success');      
                },
                error: function (xhr) {
                    alert('Error: There was some error while posting. Please try again later.');
                }
            });
    }

    //You can server side code (C#)functionSaveToTextFIle(text)
    {
        try
        {
            // The using statement automatically closes the stream and calls  // IDisposable.Dispose on the stream object. 
            using (System.IO.StreamWriter file = newSystem.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            {
                file.WriteLine(text);
            }
        }
        catch(ex)
        {
            throw ex;
        }
    }

Post a Comment for "How To Save And Edit A File Using Javascript?"