javascript - 使用 NodeJS 从 Google Cloud Storage 中的一组路径中检索和下载所有文件
问题描述
我有一个数组entryIdsWithImages
,类似于谷歌云存储中的文件夹名称,我必须从其中下载所有图像,即我想从这些特定的 GCP 路径下载所有图像。因此,根据@google-cloud/storage
文档,我首先从这些路径中检索所有文件,然后将它们下载到一个临时目录中,然后我将其压缩。但是,我发现下载的图像大小为 0B,而它们不在实际存储中。我哪里错了?
await Promise.all(
entryIdsWithImages.map(async (entryId) => {
const prefix = `images/${uid}/${entryId}`;
// download the images for the entry.
const [files] = await bucket.getFiles({
prefix,
});
files.forEach(async (file) => {
// file.name includes the whole path to the file, thus extract only the innermost path, which will be the name of the file
const fileName = file.name.slice(
file.name.lastIndexOf('/') + 1
);
const imgTempFilePath = path.join(imageDirectory, fileName);
try {
await file.download({
destination: `${imgTempFilePath}.jpg`,
});
} catch (e) {
console.log(
`Error downloading the image at ${prefix}/${fileName}: `,
e
);
}
});
})
)
我使用的版本是:"@google-cloud/storage": "^4.7.0"
. 我尝试使用最新版本,只是为了获得相同的结果。
解决方案
Cloud Storage API 代码对我来说看起来是正确的。我期待这是你的问题:
destination: `${imgTempFilePath}.jpg`,
将文件类型更改为jpg
可能会导致看起来像 0K 的损坏文件。
这段代码非常适合我的存储桶:
const downloadAll = async (bucket) => {
const imageDirectory = 'downloads';
const prefix = `READ`;
// download the images for the entry.
const [files] = await bucket.getFiles({
prefix,
});
files.forEach(async (file) => {
console.log(`file: ${file}`);
// file.name includes the whole path to the file, thus extract only the innermost path, which will be the name of the file
const fileName = file.name.slice(
file.name.lastIndexOf('/') + 1
);
const imgTempFilePath = path.join(imageDirectory, fileName);
try {
await file.download({
destination: `${imgTempFilePath}.jpg`,
});
} catch (e) {
console.log(
`Error downloading the image at ${prefix}/${fileName}: `,
e
);
}
});
}
推荐阅读
- php - 为什么当用户点击“发送”时没有出现任何错误但页面也没有刷新?
- java - 如何使用 Redis Spring Data 将两个值附加到一个键
- c# - 抛出异常:System.Xml.dll 中的“System.Xml.XPath.XPathException”
- python - 机器学习中的过度拟合术语
- c# - detectUrl 属性 Winforms C#
- ios - 如何使用 swift 实现带有 JSON 数据的搜索栏?
- php - 将以下基本 XML 文档转换为二维 PHP 数组
- javascript - removeChild - 删除第一个或最后一个节点
- angular - 直到物业的完整日历营业时间
- php - 仅在页面上显示登录用户的帖子 (Wordpress-PHP)