Skip to content
This repository has been archived by the owner on Aug 26, 2023. It is now read-only.

How to upload a file to a Web service API?

Peter Freeman edited this page Sep 1, 2019 · 1 revision

If you receive a File object via the dropzone you can read the file contents and upload it to a Web Api. See the following example:

// in app.component.ts
onFilesAdded(event) {
  console.log(event);
  this.files.push(...event.addedFiles);

  this.readFile(this.files[0]).then(fileContents => {
    // Put this string in a request body to upload it to an API.
    console.log(fileContents);
  }
}

private async readFile(file: File): Promise<string | ArrayBuffer> {
  return new Promise<string | ArrayBuffer>((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = e => {
      return resolve((e.target as FileReader).result);
    };

    reader.onerror = e => {
      console.error(`FileReader failed on file ${file.name}.`);
      return reject(null);
    };

    if (!file) {
      console.error('No file to read.');
      return reject(null);
    }

    reader.readAsDataURL(file);
  });
}
Clone this wiki locally