我正在嘗試使用 Android 相機捕獲影像并將其上傳到 AWS S3 存盤桶。使用 Angular 13 Ionic 6 和 Capacitor 相機。
最后,我將影像上傳到 S3,但嘗試在瀏覽器中查看時,出現錯誤:
image ... cannot be displayed because it contains errors
S3 存盤桶中顯示的影像大小始終為 48.5 Kb。我發現了一些帶有類似錯誤訊息的報告,但沒有任何幫助。
在我的signup.component.ts 中:
async uploadProfilePhotoToAws(txKey: string, fileName: string): Promise<string> {
let image = await this.getBase64ImageFromUrl(this.profilePhotoUrl.split(',')[1]);
var data = {
Key: 'test-key-profile-image', //txKey,
name: fileName '.jpg', //Value: profiles/09720004658354.jpg
value: image,
ContentEncoding: 'base64',
ContentType: 'image/jpeg',
type: 'image/jpeg'
};
console.log('AWS data payload: ', JSON.stringify(data));
//Upload profile image to AWS s3
return this._aws.uploadDataFile(data).then(res => {
if (res) {
console.log('aws profile file returned: ', res);
return res;
}
}).catch(err => {
console.log('AWS profile upload error: ', err);
return '';
});
}
并且:
async getBase64ImageFromUrl(imageUrl) {
var res = await fetch(imageUrl);
var blob = await res.blob();
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.addEventListener("load", function () {
resolve(reader.result);
}, false);
reader.onerror = () => {
return reject(this);
};
reader.readAsDataURL(blob);
})
}
我的add-photo.component.ts - 提供上述注冊組件:
import { Component, EventEmitter, OnInit, Output, Input } from '@angular/core';
import { PhotoService } from '../../services/photo.service';
import { CameraDirection, CameraResultType } from '@capacitor/camera';
@Component({
selector: 'app-add-photo',
templateUrl: './add-photo.component.html',
styleUrls: ['./add-photo.component.scss'],
})
export class AddPhotoComponent implements OnInit {
@Output('photo') photo = new EventEmitter<string>();
@Input() receivedPhotoPath: string;
photoPath: string = "/assets/media/avatar.svg";
constructor(public photoService: PhotoService) { }
ngOnInit() {
console.log('OnInit Received Photo Path: ', this.receivedPhotoPath);
if (this.receivedPhotoPath!='') {
this.photoPath = this.receivedPhotoPath;
}
}
capturePhoto() {
console.log('add-photo Component about to call the capturePhoto service');
this.photoService.capturePhoto(CameraDirection.Front, CameraResultType.Uri).then((photoResult: string) => {
console.log('Returned from capturePhoto: ' JSON.stringify(photoResult));
this.photoPath = photoResult;
this.photo.emit(photoResult);
}).catch((error) => {
console.log('Failed profile picture capture. Error: ' error.message);
});
}
}
還有photo.service.ts - 服務于上述 add-photo.component:
import { Injectable } from '@angular/core';
import { Camera, CameraDirection, CameraResultType, CameraSource, Photo } from '@capacitor/camera';
@Injectable({
providedIn: 'root'
})
export class PhotoService {
public photoUrl: string;
constructor() { }
public async capturePhoto(direction: CameraDirection = CameraDirection.Rear, resultType: CameraResultType = CameraResultType.Uri): Promise<string> {
const capturedPhoto = await Camera.getPhoto({
resultType: resultType,
source: CameraSource.Prompt,
direction: direction,
quality: 100
});
this.photoUrl = capturedPhoto.webPath;
return this.photoUrl;
}
}
aws-file- upload.service.ts :
import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { environment } from '../../environments/environment';
import { PromiseResult } from 'aws-sdk/lib/request';
import { PutObjectOutput } from 'aws-sdk/clients/s3';
import { AWSError } from 'aws-sdk/global';
@Injectable({
providedIn: 'root'
})
export class AwsFileUploadService {
constructor() { }
uploadDataFile(data: any) {
const contentType = data.type;
const bucket = new S3({
accessKeyId: environment.awsAccessKey,
secretAccessKey: environment.awsSecret,
region: environment.awsRegion
});
const params = {
Bucket: environment.awsBucket,
Key: data.name, //manipulate filename here before uploading
Body: data.value,
ContentEncoding: 'base64',
ContentType: contentType
};
var putObjectPromise = bucket.putObject(params).promise();
return putObjectPromise.then(function(data) {
console.log('succesfully uploaded the image! ' JSON.stringify(data));
return data;
}).catch(function(err) {
console.log(err);
return err;
});
}
}
請幫助我確定我做錯了什么。謝謝!
uj5u.com熱心網友回復:
解決方案是在將影像負載準備到 AWS S3 時使用 Buffer:
async uploadProfilePhotoToAws(txKey: string, fileName: string): Promise<string> {
console.log('Photo URL Before passed to Base64 transformation: ', this.profilePhotoUrl);
let image = await this.getBase64ImageFromUrl(this.profilePhotoUrl); //Image saved corrupt in S3. Check why
let buf = Buffer.from(image.toString().replace(/^data:image\/\w ;base64,/, ""), "base64");
var data = {
Key: txKey,
name: fileName '.jpg',
value: buf,
ContentEncoding: 'base64',
ContentType: 'image/jpeg',
type: 'image/jpeg'
};
//Upload profile image to AWS s3
return this._aws.uploadDataFile(data).then(res => {
if (res) {
console.log('aws profile file returned: ', res);
return res;
}
}).catch(err => {
console.log('AWS profile upload error: ', err);
return '';
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/472016.html
上一篇:即使安裝了應用,Firebase動態鏈接也始終會轉到ios應用商店
下一篇:反應原生:按下時更改組件道具
