即使在添加值后,获取Formdata为空。

问题描述 投票:0回答:1

我一直在尝试在我的 IONIC 4 应用程序中通过本地 http POST 请求发送图像。我得到了选定的图片和blob,但当我试图将其追加到我的formData时,我的formData总是空的。

以下是我的 ts 代码

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://kairav.rapidesk.in/api/feedback/', feedbackData, { 'Content-Type': 'multipart/form-data', 'Authorization': "Token" + " " + this.authToken })
      .then(data => {
        console.log(data);
      }).catch(err => {
        console.log(err)
      })
  }

我已经分享了我的控制台的图像。enter image description here

1)第一个控制台显示我的图像位置和数据2)第二个控制台是我的formData3)第三个控制台是我的imgBlob。

javascript angular ionic-framework ionic4 angular8
1个回答
0
投票

你不需要将图像数据绑定到FormData。请按照我的代码。这对我来说很好。它可能会帮助你。

  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);
 }
© www.soinside.com 2019 - 2024. All rights reserved.