首页 > 解决方案 > 使用 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". 我尝试使用最新版本,只是为了获得相同的结果。

标签: javascriptnode.jsgoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storage

解决方案


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
            );
        }
    });
}

推荐阅读