【问题标题】:How do I upload images from node/express REST API to Google Cloud Storage?如何将图像从 node/express REST API 上传到 Google Cloud Storage?
【发布时间】:2020-11-12 05:02:36
【问题描述】:

我正在构建一个 REST API,其中 node/express/mongoDB 部署在 Netlify 函数上(数据库直接来自 MongoDB Atlas)。我想做的是创建一个 API 路由,允许将图像作为 POST 请求中的字段之一上传。 Express 然后将此文件上传到 Google Cloud Storage,获取新上传的图片 url,并将此 url 作为文档字段之一存储在数据库中。

我想到的一个选项是使用multer。由于它被部署为无服务器功能,Express 无法访问任何存储。这意味着我无法使用multer 将图像存储在本地,并且将其保存在内存中会导致太多潜在问题(图像是视频游戏屏幕截图,因此它们非常庞大)。目前,这是不行的,或者至少不是我理想的选择。

我认为最理想的方法是以某种方式直接将此文件从 API 路由处理直接上传到 Google Cloud Storage。 This was achieved by Ben Awad,但我对他的代码知之甚少(resolversexpress.static()Mutation?)。几乎是我在每一行都拔头发。

我不知道如何在没有multer 的情况下访问从 POST 请求上传的文件,更不用说将其直接上传到 GCS。

我应该如何处理这个问题?

【问题讨论】:

    标签: node.js rest express google-cloud-storage backend


    【解决方案1】:

    也许NodeJS GCP storage client 会有所帮助

    在 Github 自述文件页面中,有几个关于如何使用节点和 GCP 存储的示例。

    Here你可以找到下面的上传示例

        function main(bucketName = 'my-bucket', filename = './local/path/to/file.txt') {
          // [START storage_upload_file]
          /**
           * TODO(developer): Uncomment the following lines before running the sample.
           */
          // const bucketName = 'Name of a bucket, e.g. my-bucket';
          // const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';
    
          // Imports the Google Cloud client library
          const {Storage} = require('@google-cloud/storage');
    
          // Creates a client
          const storage = new Storage();
    
          async function uploadFile() {
            // Uploads a local file to the bucket
            await storage.bucket(bucketName).upload(filename, {
              // Support for HTTP requests made with `Accept-Encoding: gzip`
              gzip: true,
              // By setting the option `destination`, you can change the name of the
              // object you are uploading to a bucket.
              metadata: {
                // Enable long-lived HTTP caching headers
                // Use only if the contents of the file will never change
                // (If the contents will change, use cacheControl: 'no-cache')
                cacheControl: 'public, max-age=31536000',
              },
            });
    
            console.log(`${filename} uploaded to ${bucketName}.`);
          }
    
          uploadFile().catch(console.error);
          // [END storage_upload_file]
        }
    
        main(...process.argv.slice(2));
    

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多