title: Angular 2 Synchronous File Upload
body: <p>I am trying to upload a file to web api which takes the file as byte array using angular 2 application.</p>
  
  <p>I am not able to pass the byte array from angular 2 page to web api. It looks like the File Reader read method is asynchronous. How do I make this as synchronous call or wait for the file content to be loaded before executing the next line of code?</p>
  
  <p>Below is my code</p>
  
  <pre><code>//attachment on browse - when the browse button is clicked
  //It only assign the file to a local variable (attachment)
  fileChange = (event) =&gt; {
      var files = event.target.files;
      if (files.length &gt; 0) {
          this.attachment = files[0];
      }
  }
  
  //when the submit button is clicked
  onSubmit = () =&gt; {
  
  
          //Read the content of the file and store it in local variable (fileData)
          let fr = new FileReader();
          let data = new Blob([this.attachment]);
          fr.readAsArrayBuffer(data);
          fr.onloadend  = () =&gt; {
              this.fileData = fr.result; //Note : This always "undefined"
          };
  
  
          //build the attachment object which will be sent to Web API
          let attachment: Attachment = {
              AttachmentId: '0',
              FileName: this.form.controls["attachmentName"].value,
              FileData: this.fileData
          }
  
          //build the purchase order object
          let order: UpdatePurchaseOrder = {
              SendEmail: true,
              PurchaseOrderNumber: this.form.controls["purchaseOrderNumber"].value,
              Attachment: attachment
          }
  
          //call the web api and pass the purchaseorder object
          this.updatePoService
              .updatePurchaseOrder(this.form.controls["purchaseOrderRequestId"].value, order)
              .subscribe(data =&gt; {
                  if (data) {
                      this.saveSuccess = true;
                  }
                  else {
                      this.saveSuccess = false;
                  }
              },
                  error =&gt; this.errors = error,
                  () =&gt; this.res = 'Completed'
              );
      }
  </code></pre>
  
  <p>Any hint would be useful.</p>
  
  <p>regards,
  -Alan-</p>