如何编码图像数组,然后发布它们? [英] How to encode an array of image, then post them?
问题描述
我尝试对图像列表进行编码,然后通过发布请求将它们发送到rest api. 即使经过大量的试验和失败,我也无法保证在编码后触发"post"
I try to encode a list of image, then send them via a post request to a rest api. Even after a lot of trials and fails, I can't mange to have the 'post' fired after the encodings
我不确定是否相关,但我应该说该应用程序是在Android设备上运行的离子应用程序
I'm not sure if it's relevant, but I should say that the app is an ionic app running on an android device
这是代码.触发后,blob列表为空,但是我在日志中确实得到了一个编码图像.
Here's the code. The blob list is null upon post firing, but I do get an encoded image in the log.
this.loadImages(lesObs[i].imagePath).then( async (blobList) => {
lesObs[i].imageBlobs = blobList;
this.http.post(this.url_post_one_observation, lesObs[i], { headers: this.headers })
.subscribe(
(result) => {
console.log("upload done");
}, (error) => {
this.showErrorAlert("Erreur upload : " + error.status, error.message);
});
});
private async loadImages(paths: string[]) {
let lesBlobs :string[];
paths.forEach(async (unPath) => {
let img = await this.encodeImage(unPath);
console.log ("img :" + img );
lesBlobs.push(img);
});
console.log("returning les blobs");
return lesBlobs;
}
private async encodeImage(path) {
return this.base64.encodeFile(path).then((img) => {
console.log("encoding " + path);
return img;
});
}
推荐答案
首先,您没有初始化lesBlobs
,只是对其进行了声明.您需要将其更改为let lesBlobs: string[] = [];
First, you did not initialize lesBlobs
, you just declared it. You will need to change it to let lesBlobs: string[] = [];
private async loadImages(paths: string[]) {
let lesBlobs :string[];
paths.forEach(async (unPath) => {
let img = await this.encodeImage(unPath);
console.log ("img :" + img );
lesBlobs.push(img);
});
console.log("returning les blobs");
return lesBlobs;
}
除此之外,您的lesBlobs
很可能仍会返回一个空数组,因为forEach是一个异步函数.最简单的方法是将其更改为
In addition to that, your lesBlobs
will most likely still return an empty array because the forEach is an async function. The easiest way is to change it to
for(const unPath of paths) {
let img = await this.encodeImage(unPath);
console.log ("img :" + img );
lesBlobs.push(img);
}
这篇关于如何编码图像数组,然后发布它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!