Getting the result object of FileReader()

后端 未结 2 2031
攒了一身酷
攒了一身酷 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: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(" 
    ")); }; reader.readAsDataURL(upload); }); p.then(function(elem) { elem.append("
    "); }) });
    
    
    

提交回复
热议问题