Uploadingimage to server


#1

I want to upload files to S3 server. I am able to get image from Camera and read it with file plugin:

    this.file.resolveLocalFilesystemUrl(imageData).then((entry: FileEntry) => {
      let dirPath = entry.nativeURL;
      const dirPathSegments = dirPath.split('/');
      dirPathSegments.pop();
      dirPath = dirPathSegments.join('/');

      this.file.readAsArrayBuffer(dirPath, entry.name).then((buffer) => {
        console.log(buffer);

        const imgBlob = new Blob([new Uint8Array(buffer)], {type: 'application/image-jpeg;charset=utf-8'});
        console.log(imgBlob);

        this.videoService.store('match', 118, [imgBlob])
        .subscribe(
          (event: any) => {
            // Handeling server response
          },
          (responseError) => console.log(responseError));
      });



    }).catch((err) => console.log(err));

Is there a way to send actual file and not blob or Array buffer? Or can somebody explain why it is better to send Blob or Array buffer.

Thanks


#2

You can create FormDate and append your blob and then post your form data to server.
Note: As far as I know iOS doesn’t have proper FormData support. You might need to use polyfill

...
public uploadFile(url: string, base64: string): Observable<any> {
      const blob: Blob = this.dataURItoBlob(base64);
      const fd = new FormData();
      fd.append('file[]', blob);
      return this.http.post(url, fd);
}

private dataURItoBlob(dataURI: string): Blob {
    // convert base64/URLEncoded data component to raw binary data held in a string
    let byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = encodeURI(dataURI.split(',')[1]);

    // separate out the mime component
    const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    const ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
  }