Upload File as String to JavaScript Variable

前端 未结 2 1708
长发绾君心
长发绾君心 2020-12-28 18:29

Is there any way for a client to upload a file in an HTML form (e.g. .txt or .csv formats) to a JavaScript variable as a string using only JavaScript? If so, could you prov

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 18:51

    This variation on yent's answer manages multiple uploads and uses jquery:

    HTML:

    script:

    $("#myfile").on("change", function (changeEvent) {
      for (var i = 0; i < changeEvent.target.files.length; ++i) {
        (function (file) {               // Wrap current file in a closure.
          var loader = new FileReader();
          loader.onload = function (loadEvent) {
            if (loadEvent.target.readyState != 2)
              return;
            if (loadEvent.target.error) {
              alert("Error while reading file " + file.name + ": " + loadEvent.target.error);
              return;
            }
            console.log(loadEvent.target.result.length); // Your text is in loadEvent.target.result
          };
          loader.readAsText(file);
        })(changeEvent.target.files[i]);
      }
    });
    

    Worth noting:

    • You must use one FileReader for each (concurrent) file read. Otherwise you see an exception like The object is already busy reading.
    • The loadEvent callbacks will be called in an arbitrary order, likely dependent on the size of the upload.
    • The loadEvent closure will see the i value which ended the loop.
    • FileReader results are NOT arrays; they have no forEach.

    This jsfiddle demo preserves upload order by laying out divs in the change handler.

提交回复
热议问题