android - 如何使用 Ionic / Angular 上的 FormData 从 Android 相机上传照片
问题描述
我目前正在开发一个 Android 应用程序,用户可以在其中拍摄他或她的照片并将其上传到 PATCH API 端点,该端点将监听密钥“头像”。
我正在使用Cordova Camera和Advanced 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 的经验,所以这对我来说是全新的。
解决方案
问题是 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
推荐阅读
- python - 网页正在使用 Chromedriver 作为机器人检测 Selenium Webdriver
- javascript - 使用momentjs从范围内获取几个月和几周
- serverless-framework - 在无服务器中使用标签时 API Gateway 中缺少标签
- arduino - 优化转换函数(字符串到字节)
- javascript - 将数据绑定到角度复选框
- laravel - 创建具有多个一对多关系值的数据列表
- google-app-engine - Google Cloud 函数能否与 Appengine 共享数据存储?
- neural-network - 使用“咖啡时间”对 alexnet 测试进行基准测试
- nginx - 为什么 nginx 不测试所有可用位置?
- python - Visual Studio Code - 具有自动完成功能的 Python 交互式数据科学 REPL