Not able to send image via POST api

Viewed 170

I have a requirement where I need to select an image from phone library/camera and upload to server via POST api. I am able to load the image from the library but getting an error while sending the image using the post request

My HTML Code:

<p (click)="selectImage()">Add an attachment</p></ion-item>

my .ts file:

import { HTTP } from "@ionic-native/http/ngx";

  async selectImage() {
    const actionSheet = await this.actionSheetController.create({
      header: 'select image',
      buttons: [{
        text: 'Load from library',
        handler: () => {
          this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
        }
      },
      {
        text: 'Cancel',
        role: 'cancel'
      }
      ]
    });
    await actionSheet.present();
  }


  takePicture(sourceType: PictureSourceType) {
    var options: CameraOptions = {
      quality: 100,
      sourceType: sourceType,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(imagePath => {
      if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) { 
        this.file.resolveLocalFilesystemUrl(imagePath).then((entry: FileEntry) => {
          entry.file(file => {
            console.log(file);
            this.readFile(file);
          });
        });
      }
    });
  }


   readFile(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const formData = new FormData();
      const imgBlob = new Blob([reader.result], {
        type: file.type
      });
      formData.append('file', imgBlob, file.name);     
      this.uploadImageData(formData)
    };
    reader.readAsDataURL(file);
  }


 async uploadImageData(formData) {
    let feedbackData = {
      attachment: formData,
      feedback: 'test text'
    }
    this.http.post('http://abctest.rapidesk.in/api/feedback/', feedbackData, { 'Content-Type': 'application/json', 'Authorization': "Token" + " " + this.authToken })
      .then(data => {
        console.log(data);
      }).catch(err => {
        console.log(err)
      })
  }

This is the error I am getting in the console while sending the image data via the api. enter image description here

1 Answers

You should use FormData and in your html use input type="file"

You need to append your data in form of FormData

 formData.append('file', f)

Here is the complete example with input validation How to upload a file from Angular 9 with .NET Core Web API

Your service will look like this

public uploadFile(file: FormData): Observable {
        const url = `${this.apiUrl}/upload`;
        return this.http.post(url, file);
    }

Your submit function looks like this

if (this.form.valid && files[0].name.split('.').pop() === 'excel') {
      const formData = new FormData();

      Array.from(files).forEach(f => formData.append('file', f));

      this.uploadService.uploadPdfToGetBase64(formData).subscribe(
        (res: any) => {
          this.myFileInput.nativeElement.value = '';
        },
        (errorRes: HttpErrorResponse) => {
          alert('error occured');
          this.form.reset();
          this.myFileInput.nativeElement.value = '';
        }
      );
    } else {
      alert('Invalid file selected. Only excel is allowed');
    }

Your HTML looks like this

<form [formgroup]="form">
  <div class="form-group">
    <label for="file"></label>
    <input type="file" #fileinput="" formcontrolname="fileContact" id="file" required="" (change)="handleFileInput($event.target.files)">
    <button type="button" class="btn btn-info" (click)="clearSelection()">Clear</button>
  </div>
</form>
Related