0

How can one make an HTML file to create a file or read/write to a file? Is it possible to do that?
Or is it possible in any other scripting language like JavaScript, jQuery, PHP?
I am trying to do this : User gives some information and that information is stored to a file.When user tries to read the information, information stored in the file is read.
I'm trying to make these file operations on a local storage(Hard drive).Can a HTML file create a file in its folder ( HTML folder where HTML file is located ) on local storage ?

Srivishnu
  • 759
  • 1
  • 6
  • 15
  • 1
    These are a client side operations. Would it be nice if some website reads/writes your files? It's not possible. PHP is a server side language btw. Your code written in PHP is not executed on clients' browsers. – px5x2 Apr 27 '15 at 07:49
  • 2
    If you are talking client side, using the File API you can read a file a user has chosen from a file input element, or drag and drop operation. Chrome also offers reading/writing to a sandboxed area using their [FileSystem api](http://www.html5rocks.com/en/tutorials/file/filesystem/). If you make an extension or app the browsers may have other apis that allow read/write access. You need to be more specific in which area you want, but html itself cannot do this – Patrick Evans Apr 27 '15 at 07:55
  • You can't with HTML, for the simple reason that HTML is not a real _language_ (it has no variables, no functions) but just a markup. It's just a skeleton. It's very possible, as you said, with JS/jQuery/PHP/other, but that's a way too broad question to be debated here. There are like zillions of tutorials about that, just search around. – Jeremy Thille Apr 27 '15 at 07:55
  • jQuery is not a scripting language. It is a Javascript library. – Sverri M. Olsen Apr 27 '15 at 08:07

4 Answers4

4

It is not possible to write to files*, however, it is possible to read from files that have been dragged into your web page/web application.

Reading Files

To quote Mozilla's Developer Network documentation for the function:

The readAsBinaryString method is used to start reading the contents of the specified [...] File.

The FileReader API is really easy to use, having only three functions for getting data out of a file:

  • readAsArrayBuffer
  • readAsText
  • readAsDataURL

These functions are all asynchronous. There are five events to let you know where you are in the file, and to find out if there is still data to read:

  • attribute EventHandler onloadstart;
  • attribute EventHandler onprogress;
  • attribute EventHandler onload;
  • attribute EventHandler onabort;
  • attribute EventHandler onerror;
  • attribute EventHandler onloadend;

An example from HTML5Rocks

<style>
  #progress_bar {
    margin: 10px 0;
    padding: 3px;
    border: 1px solid #000;
    font-size: 14px;
    clear: both;
    opacity: 0;
    -moz-transition: opacity 1s linear;
    -o-transition: opacity 1s linear;
    -webkit-transition: opacity 1s linear;
  }
  #progress_bar.loading {
    opacity: 1.0;
  }
  #progress_bar .percent {
    background-color: #99ccff;
    height: auto;
    width: 0;
  }
</style>

<input type="file" id="files" name="file" />
<button onclick="abortRead();">Cancel read</button>
<div id="progress_bar"><div class="percent">0%</div></div>

<script>
  var reader;
  var progress = document.querySelector('.percent');

  function abortRead() {
    reader.abort();
  }

  function errorHandler(evt) {
    switch(evt.target.error.code) {
      case evt.target.error.NOT_FOUND_ERR:
        alert('File Not Found!');
        break;
      case evt.target.error.NOT_READABLE_ERR:
        alert('File is not readable');
        break;
      case evt.target.error.ABORT_ERR:
        break; // noop
      default:
        alert('An error occurred reading this file.');
    };
  }

  function updateProgress(evt) {
    // evt is an ProgressEvent.
    if (evt.lengthComputable) {
      var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
      // Increase the progress bar length.
      if (percentLoaded < 100) {
        progress.style.width = percentLoaded + '%';
        progress.textContent = percentLoaded + '%';
      }
    }
  }

  function handleFileSelect(evt) {
    // Reset progress indicator on new file selection.
    progress.style.width = '0%';
    progress.textContent = '0%';

    reader = new FileReader();
    reader.onerror = errorHandler;
    reader.onprogress = updateProgress;
    reader.onabort = function(e) {
      alert('File read cancelled');
    };
    reader.onloadstart = function(e) {
      document.getElementById('progress_bar').className = 'loading';
    };
    reader.onload = function(e) {
      // Ensure that the progress bar displays 100% at the end.
      progress.style.width = '100%';
      progress.textContent = '100%';
      setTimeout("document.getElementById('progress_bar').className='';", 2000);
    }

    // Read in the image file as a binary string.
    reader.readAsBinaryString(evt.target.files[0]);
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Writing Files

Similar to FileReader, there was a similar API that was suggested for writing files, called... FileWriter!

However, since April 2014:

Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.

Google Chrome does have an API for writing to files on the machine, FileSystem, and it still does work for extensions, however, just like FileWriter, it also is not being developed by W3C, and so it might not be a great idea to rely on this functionality.

But all is not lost if you still want files to be generated on the client side!

I point to you to this answer, where the following function is created:

function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}

This function will force the browser to download a file with the name that you specify (on the first parameter), and the content you want (on the second parameter).

download('can_i_let_the_browser_download_this.txt', 'Yes, I can!');
Community
  • 1
  • 1
Tim Groeneveld
  • 8,739
  • 3
  • 44
  • 60
1

It is not possible in HTML but you can do it using PHP using File methods

more more information you can look into php manual

1

Do you mean local storage ?
Hope will help you.

omxian
  • 430
  • 4
  • 6
1

As already pointed out, you are mixing the server and client sides, and you are not quite specific on the result you are trying to get:

  • You can create files on the server and manipulate the files stored on that side of the road. This can be done using PHP, Server-Side JavaScript, Python, Perl... there are lots of choices. The only important thing to remember is that you can only create or modify files on that server, which can only be seen by the client if the server allows it (for example, using JavaScript to create a bunch of data, send it to the server, and have them stored there).

  • You can also create a file on the client using the FileSystem API, as pointed out by Patrick Evans.

Important to remember:

Client-side:

  • HTML (markdown to describe all the components in the website)
  • JavaScript (code that will be executed on the client)

Server-side:

  • PHP, Python, Perl, Server-Side JavaScript...: Code that will be executed on the server, usually sending a reply to clients.
martinarroyo
  • 9,389
  • 3
  • 38
  • 75