【问题标题】:Not able to send image via POST api无法通过 POST api 发送图像
【发布时间】:2020-09-29 18:13:25
【问题描述】:

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

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

这是我在通过 api 发送图像数据时在控制台中遇到的错误。

【问题讨论】:

  • 请尝试关注http.post...:,{data:formData},
  • @YunusEmreBAKAÇ 试过了,但似乎没有用,仍然出现同样的错误
  • 您发送的不是 JSON。不要对你的 API 撒谎
  • 我已更新我的问题并将对象正确传递给我的 api。那里的服务器需要文件

标签: javascript angular ionic-framework ionic4 angular8


【解决方案1】:

您应该使用 FormData 并在您的 html 中使用 input type="file"

您需要以 FormData 的形式附加您的数据

 formData.append('file', f)

这是带有输入验证的完整示例How to upload a file from Angular 9 with .NET Core Web API

您的服务将如下所示

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

您的提交函数如下所示

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');
    }

您的 HTML 如下所示

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 2018-04-27
    • 2012-11-14
    • 2021-09-14
    • 1970-01-01
    • 2017-05-22
    • 2014-10-20
    相关资源
    最近更新 更多