【问题标题】:How do i upload a photo from the Android camera with FormData on Ionic / Angular如何使用 Ionic / Angular 上的 FormData 从 Android 相机上传照片
【发布时间】:2020-02-27 14:04:41
【问题描述】:

我目前正在开发一个 Android 应用程序,用户可以在其中拍摄他或她的照片并将其上传到一个 PATCH API 端点,该端点将侦听密钥“头像”。

我正在使用Cordova CameraAdvanced HTTP 插件来处理它。

以下是拍照时触发的功能。

takePicture() {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true,  // Corrects Android orientation quirks
      allowEdit: false, // Post process aanpassingen
      sourceType: this.camera.PictureSourceType.CAMERA // Pak de selfie camera
    };
    this.camera.getPicture(options).then((imageData) => {
      const formData = new FormData();
      formData.append('avatar', imageData, 'pic.jpg');
      this.web.updateUserInfo(formData).subscribe(() => {});
    }, (err) => {
      console.error('Camera Error: ' + err);
    });
  }

这里是API处理

updateUserInfo(newData: any) {
        return new Observable((obs) => {
                this.http2.patch('localhost/user', {newData}, {
                    'X-Subdomain': 'host',
                    'X-Token': this.apiKey,
                }).then(() => {console.log('Camera API success!'); obs.next(); }).catch(error => {
                    console.error(error);
                });
        });
    }

没有给出错误,所以我很难看出问题出在哪里。我几乎没有使用 Cordova 和 Ionic 的经验,所以这对我来说是全新的。

【问题讨论】:

  • 应用程序端一切正常。 Cordova 相机为您提供 base64 图像。您必须在服务器端或要显示图像的位置进行调试。

标签: android angular ionic-framework multipartform-data


【解决方案1】:

问题是destinationType: this.camera.DestinationType.FILE_URI,

您正在通过 http 发送文件 url,而不是图像的 base64

更改您的目的地类型: destinationType: this.camera.DestinationType.DATA_URL,

DATA_URL 返回 base64 编码的字符串。 DATA_URL 可能会占用大量内存并导致应用程序崩溃或内存不足错误。尽可能使用 FILE_URI 或 NATIVE_URI

更新

在此视频中,您可以查看如何将 base64 作为 File

发送到 api

https://www.youtube.com/watch?v=tph5Nk4Ab1g

【讨论】:

  • 我是否需要像现在一样将这个 Base64 字符串放入 formData.append 中?在检查 Swagger 以获取 API 详细信息时,API 需要 Parameter Type: FormData 和 Data Type: file。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 2018-11-18
  • 2017-04-09
相关资源
最近更新 更多