Since there was a discussion yesterday about whether it is possible to read local files directly in JavaScript (i.e., not upload the contents to a server), here's an example of how it's done taken from the ProfileViewer tool I wrote a while back (http://www.iro.umontreal.ca/~dufour/tools/ProfileViewer/). Note this API requires a file selection dialog to be used. I don't think any browser will allow arbitrary access to disk. Also, there are some restrictions that vary between browsers (in particular when pages are accessed using file://). For a complete description of the API see http://dev.w3.org/2006/webapi/FileAPI.
Here are the two relevant HTML elements used in the snippet:
<input type="file" id="file" name="file" /> <button id="load" onclick="load();">Load</button>
And here's the JS code (the API is event-based, the setup is in load() and should be self-explanatory):
function load() { var selectedFile = document.getElementById("file").files[0]; var reader = new FileReader(); reader.onerror = onReadError; reader.onloadstart = onLoadStart; reader.onprogress = onProgressUpdate; reader.onload = onFileLoaded; reader.onabort = function(e) { alert('File read cancelled'); }; reader.readAsText(selectedFile); }
function onReadError(e) { switch(e.target.error.code) { case e.target.error.NOT_FOUND_ERR: alert('File Not Found!'); break; case e.target.error.NOT_READABLE_ERR: alert('File is not readable'); break; case e.target.error.ABORT_ERR: break; // noop default: alert('An error occurred reading this file.'); }; }
function onFileSelected(e) { btnLoad.disabled = false; }
function onProgressUpdate(e) { if (e.lengthComputable) { var perc = Math.round((e.loaded / e.total) * 100); $("#progress").progressbar("value", perc); } }
function onLoadStart(e) { activity.textContent = "Loading file..."; $("#progress").show(); $("#progress").progressbar("value", 0); }
function onFileLoaded(e) { $("#progress").progressbar("value", 100); activity.textContent = "File loaded"; $("#progress").hide(); data = e.target.result; // process data here }
Afficher les réponses par date
Intéressant. Il y a un FileReader API mais pas encore de FileWriter (!)
- Maxime