【问题标题】:Node.js Google Cloud Storage Get Multiple Files' MetadataNode.js Google Cloud Storage 获取多个文件的元数据
【发布时间】:2021-01-20 06:03:52
【问题描述】:

我在 Google Cloud Storage 上有多个文件,分别命名为 0.jpg、1.jpg、2.jpg 等。我想获取每个文件的元数据,而无需单独设置文件名。然后,想要将这些元数据信息发送到 React 应用程序。在 React 应用程序中,当单击图像时,弹出窗口会显示该单击图像的元数据信息。

对于一个文件,我使用了以下代码:

const express = require("express");
const cors = require("cors");
// Imports the Google Cloud client library
const { Storage } = require("@google-cloud/storage");

const bucketName = "bitirme_1";
const filename = "detected/0.jpg";

const storage = new Storage();

const app = express();

app.get("/api/metadata", cors(), async (req, res, next) => {
  try {

    // Gets the metadata for the file
    const [metadata] = await storage
      .bucket(bucketName)
      .file(filename)
      .getMetadata();

    const metadatas = [
      {id: 0, name: `Date: ${metadata.updated.substring(0,10)}, Time: ${metadata.updated.substring(11,19)}`},
      {id: 1, name: metadata.contentType}
    ];

    res.json(metadatas);
  } catch (e) {
    next(e);
  }
});

const port = 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

我首先设置了存储桶名称。然后,设置文件名数组为(89为文件数):

const filename = Array(89).fill(1).map((_, i) => ('detected/' + i + '.jpg'));

这些文件位于检测到的文件夹中。当我尝试这个时,它给了我这个错误:

错误:没有这样的对象:bitirme_1/detected/0.jpg、detected/1.jpg、detected/2.jpg、detected/3.jpg、detected/4.jpg、detected/5.jpg、detected/6 .jpg, ....

如何解决获取多个文件的元数据问题?

另外,我想获取存储桶(或检测到的文件夹)中的文件数。我搜索了 API,但找不到任何东西。我不想输入文件总数为 89,想从 API 中获取。

【问题讨论】:

  • 您是否使用库来获取元数据?如果有,是哪一个?您可以edit 您的帖子包含详细信息,包括获取元数据的代码。
  • 我正在使用 google-cloud/storage api 来获取元数据信息。我只用一个文件试过这个。我为它添加了代码
  • 您能否编辑您的问题以包含您使用库的 sn-p 和filename
  • 我在一分钟前的问题中添加了它
  • 哎呀!看起来我的客户缓存了旧问题。谢谢!

标签: node.js reactjs google-cloud-platform metadata


【解决方案1】:

我找到了查找存储桶中文件数量或存储桶中文件夹数量的解决方案。这是解决方案:

const [files] = await storage.bucket(bucketName).getFiles();

const fileStrings = files.map(file => file.name);

const fileSliced = fileStrings.map(el => el.slice(9, 11));

for (i = 0; i < fileSliced.length; i++) {
  if (fileSliced[i].includes('.')) {
    fileSliced[i] = fileSliced[i].slice(0, 1);
  }
}

const fileNumbers = fileSliced.map(function(item) {
  return parseInt(item, 10);
});

const numOfFiles = Math.max(...fileNumbers) + 1;

console.log(numOfFiles);

首先,我在一个字符串数组中获得了所有文件名的文件。就我而言,文件名是detected/0.jpg、detected/1.jpg、detected/2.jpg等。我只想要文件名的数字部分;因此,我从第 9 个索引到第 11 个索引(不包括在内)对字符串数组进行了切片。结果,我只得到了除一位数字之外的数字。

处理一位数字的情况,其中有 '.'在切片名称的末尾,我还删除了“。”来自这些一位数字的文件名。

结果,我得到了 ['0', '1', '2', '3', ...]。接下来,我使用 parseInt 函数将此字符串数组转换为数字数组。最后,为了得到文件的数量,我得到了数组的最大值并将这个数字加1。

我有一个图像详细信息组件,其中包括发件人 ip 的位置、下载选项和退出弹出页面。此详细信息弹出页面在 /#i 处打开,其中 i 是图像文件的名称,例如 1.jpg、2.jpg。因此,例如,当我单击第一张图片时,弹出页面会在 /#1 处打开。在这个弹出页面中,我想获取打开的图像的元数据信息。但是,我找不到解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2019-08-22
    • 2013-08-22
    • 2015-03-29
    • 2020-11-14
    • 2019-04-10
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多