android - Ionic Android:拍摄相机照片并将其发送到服务器
问题描述
几天来,我一直在努力用手机相机拍照,使用 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
看着这个参考帖子,我什至切掉了图像前面显示的多余字符,但我没有设法解决问题。
让我知道是否应该添加任何其他信息。谢谢您的帮助!
解决方案
我设法通过使用在屏幕上显示图像:
let b64 = 'data:image/jpeg;base64,' + imageData;
this.image = b64;
代替
this.image = (<any>window).Ionic.WebView.convertFileSrc(imageData);
不幸的是,this.imageData 仍然未定义,我不知道为什么。更新:看起来照片现在已发送到 bakend,但其大小为 0,后端(即 Nodejs)无法使用它。我应该怎么办?我应该以某种方式解析它吗?谢谢!
推荐阅读
- javascript - 如何在 ES6 类中的原型上设置变量?
- python - matplotlib 条形图中的两个图例
- java - Neo4j 3.5 中的事务没有实现 java.lang.AutoCloseable
- javascript - 升级 Gulp 3 到 Gulp 4 无需重新加载 BrowserSync
- php - 警告:mkdir():symfony 中的权限被拒绝
- ilnumerics - 如何更改使用相机查看的 ILNumerics 场景中的缩放中心点
- google-apps-script - 下拉以根据下拉菜单隐藏行
- php - 为什么这个查询不能正常工作?
- unicode - .net 上的奇怪标准化
- firebase - Firebase 托管配置,重写除一个 url 之外的所有内容