首页 > 解决方案 > 如何使用 Ionic / Angular 上的 FormData 从 Android 相机上传照片

问题描述

我目前正在开发一个 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 的经验,所以这对我来说是全新的。

标签: androidangularionic-frameworkmultipartform-data

解决方案


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

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

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

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

更新

在此视频中,您可以查看如何将base64作为文件发送到 api

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


推荐阅读