Peter Kusza
Peter Kusza

Reputation: 481

Ionic 3 File-Transport multipart/form-data

i am actually working on a mobile app in ionic v3 with angular5

The goal is to be able to take a picture or choose from existing ones and then upload it to the server. The first part is done, but i am struggling with the upload.

The api needs multipart/form-data which must consist of two requests. First with text part and second is the image.

Is there any solution for this?

Upvotes: 2

Views: 3694

Answers (1)

Prashant
Prashant

Reputation: 1385

This is what I have done for similar requirement

takePhoto() {
    this.camera.getPicture({
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.CAMERA,
      encodingType: this.camera.EncodingType.PNG,
      saveToPhotoAlbum: true
    }).then(imageData => {
      this.myPhoto = imageData;
      this.uploadPhoto(imageData);
    }, error => {
      this.functions.showAlert("Error", JSON.stringify(error));
    });
  }

  selectPhoto(): void {
    this.camera.getPicture({
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,
      quality: 100,
      encodingType: this.camera.EncodingType.PNG,
    }).then(imageData => {
      this.myPhoto = imageData;
      this.uploadPhoto(imageData);
    }, error => {
      this.functions.showAlert("Error", JSON.stringify(error));
    });
  }
  private uploadPhoto(imageFileUri: any): void {
    this.file.resolveLocalFilesystemUrl(imageFileUri)
      .then(entry => (<FileEntry>entry).file(file => this.readFile(file)))
      .catch(err => console.log(err));

  }
  private readFile(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const formData = new FormData();
      const imgBlob = new Blob([reader.result], { type: file.type });
      formData.append('evaluationID', this.currentEvaluation.evaluationId);
      formData.append('standardID', this.currentEvaluation.id);
      formData.append('score', this.currentEvaluation.score);
      formData.append('comment', this.currentEvaluation.comment);
      formData.append('file', imgBlob, file.name);
      this.saveStandard(formData);
    };
    reader.readAsArrayBuffer(file);
  }

And here is code for provider

saveStandard(receivedStandardInfo:any){
    return new Promise((resolve, reject) => {
      this.http.post(apiSaveStandard,receivedStandardInfo)
        .subscribe(res => {
          resolve(res);
        }, (err) => {
          console.log(err);
          reject(err);
        });
    }).catch(error => { console.log('caught', error.message); });
  }

Upvotes: 3

Related Questions