首页 > 解决方案 > Ionic Android:拍摄相机照片并将其发送到服务器

问题描述

几天来,我一直在努力用手机相机拍照,使用 Ionic 和 Android 设备,并在发布请求中将其发送到服务器。(可选)我想将图像显示到屏幕上。我阅读了很多以前有类似问题的帖子,但没有一个解决方案对我有用。我想提一下,我对离子世界还很陌生,所以我还在学习。也许这是一个我看不到的愚蠢问题。在添加我尝试过的代码之前,我想列出到目前为止我尝试过的事情:

请看下面我尝试的代码:

这是拍照的代码:

const options: CameraOptions = { // photo options
    quality: 50,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
} // take picture
this.camera.getPicture(options).then((imageData) => {
        this.imageData = imageData;
        this.image = ( < any > window).Ionic.WebView.convertFileSrc(imageData);
        //extra http://localhost/file.. and I slice it to remove extra chars
        this.image = this.image.slice(27);
    },
    (err) => {
        this.helperService.showAlert(JSON.stringify(err));
    });

这是将照片上传到服务器的代码:

upload() { // upload method
    let url = 'url/to/post';
    const date = new Date().valueOf();
    const imageName = date + '.jpeg';
    console.log(this.imageData);
    -- - > undefined
    //slice it to remove extra chars
    this.imageData = this.imageData.slice(27);
    const imageBlob = this.dataURItoBlob(this.imageData);
    const imageFile = new File([imageBlob], imageName, {
        type: 'image/jpeg'
    });
    let postData = new FormData();
    postData.append('file', imageFile);
    let data: Observable < any > = this.httpClient.post(url, postData);
    data.subscribe((result) => {
        this.helperService.showSuccess(result);
    });
}

这是blob函数:

dataURItoBlob(dataURI) {
    const byteString = window.atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
        int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array], {
        type: 'image/jpeg'
    });
    return blob;
}

这是我的 HTML 文件:

<ion-content>
    <ion-grid>
        <img [src]="DomSanitizer.bypassSecurityTrustUrl(image)">
    </ion-grid>
    <ion-button (click)="upload()" color="success">
        <ion-icon slot="icon-only" name="checkmark"></ion-icon>
    </ion-button>
</ion-content>

问题:

  1. 照片未显示在屏幕上,我的图像未定义 - 我尝试使用和不使用 DomSanitizer
  2. this.imageData 在upload()方法中未定义

这是我关注的参考帖子,但我无法看到问题: Capture and upload image to server using Ionic 4

看着这个参考帖子,我什至切掉了图像前面显示的多余字符,但我没有设法解决问题。

让我知道是否应该添加任何其他信息。谢谢您的帮助!

标签: androidangularionic-frameworkionic-native

解决方案


我设法通过使用在屏幕上显示图像:

let b64 = 'data:image/jpeg;base64,' + imageData;
  this.image = b64;

代替

this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);

不幸的是,this.imageData 仍然未定义,我不知道为什么。更新:看起来照片现在已发送到 bakend,但其大小为 0,后端(即 Nodejs)无法使用它。我应该怎么办?我应该以某种方式解析它吗?谢谢!


推荐阅读