几天以来,我一直在努力用手机相机拍照,使用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>
问题:
这是我关注的参考文章,但是我无法看到问题所在: Capture and upload image to server using Ionic 4
看着这篇参考文章,我甚至将显示在图像前面的多余字符都切了,但是我没有设法解决问题。
让我知道是否应该添加任何其他信息。谢谢您的帮助!
答案 0 :(得分:0)
我设法使用以下方法在屏幕上显示图像:
let b64 = 'data:image/jpeg;base64,' + imageData;
this.image = b64;
代替
this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);
不幸的是,this.imageData仍未定义,我不知道为什么。 更新:看起来照片已立即发送到bakend,但其大小为0,后端(即Nodejs)无法使用它。我该怎么办?我应该以某种方式解析它吗? 谢谢!