如何使用nodejs从Google云存储获取链接文件

问题描述

嗨,我正在尝试制作一些网站,例如流视频, 所以我用了react(client),node(server),mangodb(database),google cloude storage(视频的cloude storace)

我的问题是,如何从nodejs导入文件到GCS并获取链接,所以我可以将链接保存到mangodb中,并且可以将视频流式传输到客户端,谢谢:D

解决方法

与其将文件的URL保存到Mongodb,不如生成一个signed url。这将使用户可以临时访问该文件。这样,您可以控制哪些人可以轻松访问您的视频。另一方面,如果您不使用此方法,则将被迫公开文件,任何人都可以访问它们,我想那不是您想要的。

要生成签名的url,请查看下面的示例

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

// Creates a client
const storage = new Storage();
async function generateSignedUrl() {
  // These options will allow temporary read access to the file
  const options = {
    version: 'v2',// defaults to 'v2' if missing.
    action: 'read',expires: Date.now() + 1000 * 60 * 60,// one hour
  };

  // Get a v2 signed URL for the file
  const [url] = await storage.bucket(bucketName).file(filename).getSignedUrl(options);

  console.log(`The signed url for ${filename} is ${url}.`);
}