Getting the result object of FileReader()

后端 未结 2 2030
攒了一身酷
攒了一身酷 2021-01-29 09:00

is there any way i can fetch the result object of a FileReader() without getting through a function ?

i have made a sample code below:

HTML

相关标签:
2条回答
  • 2021-01-29 09:20

    The FileReader is asynchronous, so logic execution continues on past the load event handler while it waits for the file to be read. This means that (as with any async handler) all code reliant on the async event must be placed within the event handler. Try this:

    var reader = new FileReader();
    reader.onload = function() {
        code = reader.result;
        $("div").append("<label>this should appear first: " + code + "</label> <br />");
        $("div").append("<label> this should appear last: " + code + "</label> <br />");
    };
    reader.readAsDataURL(upload);
    
    0 讨论(0)
  • 2021-01-29 09:39

    is there any way i can fetch the result object of a FileReader() without getting through a function ?

    No. FileReader() is asynchronous. You can use Promise to achieve expected result

    var code = "lorem ipsum";
    
        $("input[type='file']").change(function() {
          var upload = this.files[0];
          var p = new Promise(function(resolve) {
            var reader = new FileReader();
            reader.onload = function() {
              code = reader.result;
              // pass `div` as resolve `Promise` to `.then()`
              resolve($("div").append("<label>this should appear first: " 
                                      + code + "</label> <br />"));
            };
            reader.readAsDataURL(upload);
          });
          p.then(function(elem) {
            elem.append("<label> this should appear last: " 
                        + code + "</label> <br />");
          })
    
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <input type="file" />
    <div></div>

    0 讨论(0)
提交回复
热议问题