0

I have been trying to send an image via native http POST request in my IONIC 4 app. I am getting the selected image and blob but when I am trying to append the same to my formData, my formData is always empty.

Here is my ts code

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 imgBlob = new Blob([reader.result], {
        type: file.type
      });
      const formData = new FormData();
      formData.append('file', imgBlob, file.name);
      console.log(formData) 
      console.log(imgBlob)     
      this.uploadImageData(formData)
    };
    reader.readAsArrayBuffer(file);
  }

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

I have shared the image of my console. enter image description here

  1. First console shows my image location and data
  2. Second console is my formData
  3. Third console is my imgBlob
Ravi Shah
  • 105
  • 1
  • 11

1 Answers1

0

You don't need to bind the image data to FormData. Please follow my code. This works fine with me. It may help you.

  getFileFromCamera() {
this.translate.get(["FILE_ADDED_SUCCESSFULLY", "UNABLE_TO_TAKE_PHOTO"]).subscribe(
  (values) => {
    this.camera.getPicture({
      destinationType: this.camera.DestinationType.DATA_URL,
      targetWidth: 500,
      targetHeight: 500,
      quality: 100,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true
    }).then((data) => {
      const imageData = 'data:image/jpg;base64,' + data;
      this.AddDocumentForm.patchValue({'form_file': imageData}); // I am using reactive form group but you can directly add to the API body. 
    }, (err) => {
      console.log(err);
      this.csp.showToastMessage(2, values.UNABLE_TO_TAKE_PHOTO);
    })
  });
 }

saveImage() {
   this.api.post(endPoint, {image : this.AddDocumentForm.value.form_file).subscribe(()=>{
        console.log(res);
   });
 }

// API service 
 post(endpoint: string, body: any, reqOpts?: any) {
      return this.http.post(this.url + '?' + endpoint, body, reqOpts);
 }
sibabrat swain
  • 1,277
  • 8
  • 20
  • When I am trying to send the data to my api it says that "The submitted data was not a file. Check the encoding type on the form". – Ravi Shah Jun 12 '20 at 09:51
  • did you follow the above? are you sending mime type `const imageData = 'data:image/jpg;base64,' + data;` ? check that once. do `console.log()` – sibabrat swain Jun 12 '20 at 09:53
  • Yes I did this: ```this.camera.getPicture({ destinationType: this.camera.DestinationType.DATA_URL, targetWidth: 500, targetHeight: 500, quality: 100, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, correctOrientation: true }).then((data) => { const imageData = 'data:image/jpg;base64,' + data; this.uploadImageData(imageData) })``` – Ravi Shah Jun 12 '20 at 09:55
  • console.log(imageData) gave me a big text starting with data:image/jpg;base64,/9j***** Also the api is written in Python Django – Ravi Shah Jun 12 '20 at 09:59
  • I can see from your console.log(). It is right. You are basically sending base64 image data. Follow this to upload in Django `https://stackoverflow.com/a/39587386/9739044` – sibabrat swain Jun 12 '20 at 10:19
  • Please check your browser network header as well. It should look something like this. `shorturl.at/jrxyP` Check what are you sending in API – sibabrat swain Jun 12 '20 at 10:32
  • Yes I am getting the console similar to what you have shared. – Ravi Shah Jun 12 '20 at 10:34
  • Also if I am declaring data:image/jpg;base64,' + data so can I attach png format image too? – Ravi Shah Jun 12 '20 at 10:36
  • Follow the base64 image to upload in Django and you are ready to go. – sibabrat swain Jun 12 '20 at 10:36
  • There are two things. Uploading from the native device by taking images and from the directory. If you are sending by taking images in run time then the above code will work. Do you want to upload it from Directory as well? – sibabrat swain Jun 12 '20 at 10:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215812/discussion-between-sibabrat-swain-and-ravi-shah). – sibabrat swain Jun 12 '20 at 11:29