angular - 在角度离子中将图像上传到 s3bucket 时获取白色小图片
问题描述
我有“add-property.service.ts”服务文件,其中包含 API 调用和图像上传到 s3 等内容。这是我将图像上传到 s3 的代码。我使用 ionic 文档将图片保存在函数“addNewToGallery()”中,然后将其转换为“.jpeg”扩展名,然后转换为 base 64。
现在,当点击表单提交按钮时,我调用此函数“uploadingImagesToS3Bucket()”将上述保存的图像上传到 s3。在将它上传到 s3 时,我在图片中得到了一个白色的小盒子,但不是我想要的实际图片。
在我的“s3.service.service.ts”文件中,您可以检查上传代码。我认为这里的缓冲区不起作用我也尝试应用“buffer.form”,但结果是一样的。现在我不知道问题是什么,请帮我解决这个问题,因为我是离子角度的新手。
如果您认为不需要转换为 .jpeg 和 base64,请告诉我,我将更改我的代码。在上传转换“blob”地址之前,我只添加了它们以正确格式上传图片。
//添加-property.service.ts :
//S3-Sevice
import { S3ServiceService } from '../../services/s3-service/s3-service.service';
.
.
export class AddPropertyService {
constructor(
public s3:S3ServiceService
) { }
.
.
public async addNewToGallery() {
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri,
source: CameraSource.Camera,
quality: 100
});
// Save the picture and add it to photo collection
const savedImageFile = await this.savePicture(capturedPhoto);
this.photos.unshift(savedImageFile);
}
uploadImage(image) {
return new Promise((resolve) => {
this.s3.upload(image) //HERE IM USING UPLOAD FUNCTION FROM S3.SERVICE.SERVICE.TS FILE
.then(
res => {
// console.log("RESULT",res);
// alert("Image uploaded!");
resolve(res["Location"])
this.locationOfImages.unshift(res["Location"]);
//console.log(this.locationOfImages)
},
err => {
console.log("ERROR",err);
alert("Error in image upload!");
}
);
})
}
public uploadingImagesToS3Bucket(): Promise<any>{ //THIS IS THE FUNCTION I CALL FROM MY ADD-PROPERTY.SERVICE.TS FILE ON CLICKING SUBMITTING FORM BUTTON
let promises = []
for (let photo of this.photos) {
promises.push(this.uploadImage(photo.filepath));
}
return Promise.all(promises)
}
private async savePicture(cameraPhoto: CameraPhoto) {
// Convert photo to base64 format, required by Filesystem API to save
const base64Data = await this.readAsBase64(cameraPhoto);
console.log(cameraPhoto,"cameera photo");
// Write the file to the data directory
const fileName = new Date().getTime() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: FilesystemDirectory.Data
});
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: cameraPhoto.webPath
};
}
private async readAsBase64(cameraPhoto: CameraPhoto) {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(cameraPhoto.webPath!);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
}
//s3.service.service.ts :
import * as aws from "aws-sdk";
.
.
export class S3ServiceService {
constructor() { }
async upload(image) {
return new Promise((resolve, reject) => {
var s3 = new aws.S3({
accessKeyId: environment.ID,
secretAccessKey: environment.SECRET,
params: { Bucket: environment.S3.BUCKET_NAME }
});
let buf = new Buffer(image, "base64");
console.log(buf,"buffer");
var data = {
Bucket: environment.S3.BUCKET_NAME,
Key: image,
Body: buf,
ContentEncoding: "base64",
ContentType: "image/jpeg"
};
s3.upload(data, (err, res) => {
if (err) {
reject(err);
console.log("Reject",err);
}
//console.log(`File uploaded successfully. ${res.Location}`);
else {
resolve(res);
}
});
});
}
解决方案
通过将base64更改为字节码来解决它。在上述函数中进行了以下更改,现在图像正在上传到 s3 存储桶。
//添加-property.service.ts :
public async addNewToGallery() {
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri,
source: CameraSource.Camera,
quality: 100,
allowEditing:true
});
// Save the picture and add it to photo collection
const savedImageFile = await this.savePicture(capturedPhoto);
var afterDot = savedImageFile.image.substr(savedImageFile.image.indexOf(',') + 1 );
const rawData = atob(afterDot);
const bytes = new Array(rawData.length);
for (var x = 0; x < rawData.length; x++) {
bytes[x] = rawData.charCodeAt(x);
}
this.photos.unshift({
webviewPath:capturedPhoto.webPath,
filepath: savedImageFile.filepath,
image: bytes
});
}
uploadImage(image) {
return new Promise((resolve) => {
this.s3.upload(image)
.then(
res => {
// console.log("RESULT",res);
// alert("Image uploaded!");
resolve(res["Location"])
this.locationOfImages.unshift(res["Location"]);
//console.log(this.locationOfImages)
},
err => {
console.log("ERROR",err);
alert("Error in image upload!");
}
);
})
}
public uploadingImagesToS3Bucket(): Promise<any>{
let promises = []
for (let photo of this.photos) {
promises.push(this.uploadImage(photo));
}
return Promise.all(promises)
}
private async savePicture(cameraPhoto: CameraPhoto) {
// Convert photo to base64 format, required by Filesystem API to save
const base64Data = await this.readAsBase64(cameraPhoto);
console.log(cameraPhoto,"cameera photo");
// Write the file to the data directory
const fileName = new Date().getTime() + '.'+cameraPhoto.format;
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: FilesystemDirectory.Data
});
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
image: base64Data
};
}
private async readAsBase64(cameraPhoto: CameraPhoto) {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(cameraPhoto.webPath!);
const blob = await response.blob();
return await this.convertBlobToBase64(blob) as string;
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
//s3.service.service.ts :
async upload(image) {
return new Promise((resolve, reject) => {
console.log(image)
var s3 = new aws.S3({
accessKeyId: environment.ID,
secretAccessKey: environment.SECRET,
params: { Bucket: environment.S3.BUCKET_NAME }
});
let buf = new Buffer(image.image, "base64");
console.log(buf,"buffer");
var data = {
Bucket: environment.S3.BUCKET_NAME,
Key: image.filepath,
Body: buf,
ContentEncoding: "base64",
ContentType: "image/jpeg"
};
s3.upload(data, (err, res) => {
if (err) {
reject(err);
console.log("Reject",err);
}
//console.log(`File uploaded successfully. ${res.Location}`);
else {
resolve(res);
}
});
});
}
推荐阅读
- postgresql - 将 WITH 子查询的输出复制到 postgres 中的 CSV
- node.js - 将 cypress.io 测试用例交给非技术用户
- javascript - Firebase onMessage 未触发
- python - 初始化在父类中使用的子类中的属性
- html - 如何使高度不等的列之间具有相同的边距
- c# - 在将 word 转换为 pdf 时在服务器中出现此错误,在本地运行良好,但在 iis 8.5 上上传后出现此错误
- react-native - React native / API Flatlist 新添加的自动加载数据,无需重新加载
- python-3.x - 如何使用 openpyxl 在 ChartSheet 中创建/添加多个图表?
- java - 使用同步方法禁用事件侦听器
- excel - Powershell excel添加公式 - “公式包含无法识别的文本。”