read-local-file-api.html 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. ---
  2. title: "Reading a local file with the File API"
  3. layout: default
  4. section: example
  5. ---
  6. <h3>Choose the local(s) zip file(s)</h3>
  7. <p class="note">Note : your browser will process the zip file, don't choose a file too big !</p>
  8. <input type="file" id="file" name="file" multiple /><br />
  9. <div id="error_block" class="alert alert-danger hidden">
  10. You will need a recent browser to use this demo :(
  11. </div>
  12. <div id="result_block" class="hidden">
  13. <h3>Content :</h3>
  14. <div id="result"></div>
  15. </div>
  16. <script type="text/javascript" src="{{site.baseurl}}/test/jquery-1.8.3.min.js"></script>
  17. <script type="text/javascript">
  18. (function () {
  19. if (!window.FileReader || !window.ArrayBuffer) {
  20. $("#error_block").removeClass("hidden").addClass("show");
  21. return;
  22. }
  23. var $result = $("#result");
  24. $("#file").on("change", function(evt) {
  25. // remove content
  26. $result.html("");
  27. // be sure to show the results
  28. $("#result_block").removeClass("hidden").addClass("show");
  29. // see http://www.html5rocks.com/en/tutorials/file/dndfiles/
  30. var files = evt.target.files;
  31. for (var i = 0, f; f = files[i]; i++) {
  32. var reader = new FileReader();
  33. // Closure to capture the file information.
  34. reader.onload = (function(theFile) {
  35. return function(e) {
  36. var $title = $("<h4>", {
  37. text : theFile.name
  38. });
  39. $result.append($title);
  40. var $fileContent = $("<ul>");
  41. try {
  42. var dateBefore = new Date();
  43. // read the content of the file with JSZip
  44. var zip = new JSZip(e.target.result);
  45. var dateAfter = new Date();
  46. $title.append($("<span>", {
  47. text:" (parsed in " + (dateAfter - dateBefore) + "ms)"
  48. }));
  49. // that, or a good ol' for(var entryName in zip.files)
  50. $.each(zip.files, function (index, zipEntry) {
  51. $fileContent.append($("<li>", {
  52. text : zipEntry.name
  53. }));
  54. // the content is here : zipEntry.asText()
  55. });
  56. // end of the magic !
  57. } catch(e) {
  58. $fileContent = $("<div>", {
  59. "class" : "alert alert-danger",
  60. text : "Error reading " + theFile.name + " : " + e.message
  61. });
  62. }
  63. $result.append($fileContent);
  64. }
  65. })(f);
  66. // read the file !
  67. // readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
  68. reader.readAsArrayBuffer(f);
  69. // reader.readAsBinaryString(f);
  70. }
  71. });
  72. })();
  73. </script>