无法通过POST api发送图像

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

我有一个需要从手机库/相机中选择图像并通过POST API上传到服务器的要求。我能够从库中加载图像,但是在使用发布请求发送图像时出现错误]

我的HTML代码:

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

我的.ts文件:

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

这是我通过api发送图像数据时出现在控制台中的错误。enter image description here

我有一个需要从手机库/相机中选择图像并通过POST API上传到服务器的要求。我能够从库中加载图像,但是在发送...

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

您应该使用FormData,并且在html中使用input type =“ file”

© www.soinside.com 2019 - 2024. All rights reserved.