【发布时间】:2020-05-14 18:43:54
【问题描述】:
几天来,我一直在努力用手机相机拍照,使用 Ionic 和 Android 设备,并在发布请求中将其发送到服务器。 (可选)我想将图像显示到屏幕上。 我阅读了很多以前有类似问题的帖子,但没有一个解决方案对我有用。我想提一下,我对离子世界还很陌生,所以我还在学习。也许这是一个我看不到的愚蠢问题。 在添加我尝试过的代码之前,我想列出我迄今为止尝试过的东西:
- 将 FILE_URL 和 DATA_URL 用于 destinationType 选项
- 手动将图像转换为 base 64
- 在 .html 文件中使用了 domSanitizer.bypassSecurityTrustUrl(b64img)
请看下面我尝试过的代码:
这是拍照的代码:
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>
问题:
- 照片未显示在屏幕上,我的图像未定义 - 我尝试使用和不使用 DomSanitizer
- this.imageData 在 upload() 方法中未定义
这是我关注的参考帖子,但我无法看到问题: Capture and upload image to server using Ionic 4
看了这篇参考帖,我连图片前面显示的多余字符都切掉了,但我没能解决问题。
如果我应该添加任何其他信息,请告诉我。感谢您的帮助!
【问题讨论】:
标签: android angular ionic-framework ionic-native