【问题标题】:Upload a file to Google Cloud, in a specific directory将文件上传到 Google Cloud 的特定目录中
【发布时间】:2017-03-03 18:59:12
【问题描述】:

如何在 Google Cloud 上的特定存储桶目录(例如 foo)中上传文件?

"use strict";

const gcloud = require("gcloud");

const PROJECT_ID = "<project-id>";

let storage = gcloud.storage({
  projectId: PROJECT_ID,
  keyFilename: 'auth.json'
});

let bucket = storage.bucket(`${PROJECT_ID}.appspot.com`)
bucket.upload("1.jpg", (err, file) => {
    if (err) { return console.error(err); }
    let publicUrl = `https://firebasestorage.googleapis.com/v0/b/${PROJECT_ID}.appspot.com/o/${file.metadata.name}?alt=media`;
    console.log(publicUrl);
});

我试过了:

bucket.file("foo/1.jpg").upload("1.jpg", ...)

但是那里没有upload 方法。

如何在foo 目录中发送1.jpg

在 Firebase 中,在客户端,我这样做:

ref.child("foo").put(myFile);

【问题讨论】:

    标签: node.js google-cloud-storage


    【解决方案1】:

    我认为只需将 foo/ 添加到文件名中就可以了,就像 bucket.upload("foo/1.jpg", (err, file) ... 在 GCS 中,目录只需在文件名中添加一个“/”即可。

    【讨论】:

      【解决方案2】:
      bucket.upload("1.jpg", { destination: "YOUR_FOLDER_NAME_HERE/1.jpg" }, (err, file) => {
          //Do something...
      });
      

      这会将1.jpg 放入YOUR_FOLDER_NAME_HERE 文件夹中。

      Here 是文档。顺便说一句,gcloud 已弃用,您应该改用google-cloud

      【讨论】:

        【解决方案3】:

        如果从同一个项目中访问 projectId , keyFilename,.. 不需要,我使用下面的代码进行上传和下载,它工作正常。

        // Imports the Google Cloud client library
        const Storage = require('@google-cloud/storage');
        const storage = new Storage();
        var destFilename = "./test";
        var bucketName = 'cloudtesla';
        var srcFilename = 'test';
        
          const options = {
            destination: destFilename,
          };
        
        
        //upload file
        console.log("upload Started");
        storage.bucket(bucketName).upload(srcFilename, {}, (err, file) => {
        
                if(!err)
                console.log("upload Completed");
                else
                console.log(err);
        });
        
        
        //Download file
        console.log("Download Started");
          storage
            .bucket(bucketName)
            .file(srcFilename)
            .download(options)
            .then(() => {
              console.log("Download Completed");
            })
            .catch(err => {
              console.error('ERROR:', err);
            });
        

        【讨论】:

          【解决方案4】:

          给你...

          const options = {
            destination: 'folder/new-image.png',
            resumable: true,
            validation: 'crc32c',
            metadata: {
              metadata: {
                event: 'Fall trip to the zoo'
              }
            }
          };
          
          bucket.upload('local-image.png', options, function(err, file) {
            // Your bucket now contains:
            // - "new-image.png" (with the contents of `local-image.png')
          
            // `file` is an instance of a File object that refers to your new file.
          });
          

          【讨论】:

            【解决方案5】:

            如果您想在将文件上传到存储桶时使用 async-await,回调将无法完成这项工作,这就是我的做法。

            async function uploadFile() {
                const destPath = 'PATH_TO_STORAGE/filename.extension';
            
                await storage.bucket("PATH_TO_YOUR_BUCKET").upload(newFilePath, {
                    gzip: true,
                    destination: destPath,  
                });
            }
            

            希望它可以帮助某人!

            【讨论】:

              【解决方案6】:

              2020 年更新

              根据谷歌文档:

              const { Storage } = require('@google-cloud/storage');
              const storage = new Storage()
              const bucket = storage.bucket('YOUR_GCLOUD_STORAGE_BUCKET')
              const blob = bucket.file('youFolder/' + 'youFileName.jpg')
              
              const blobStream = blob.createWriteStream({
                  resumable: false,
                  gzip: true,
                  public: true
              })
              
              blobStream.on('error', (err) => {
                  console.log('Error blobStream: ',err)
              });
              
              blobStream.on('finish', () => {
              // The public URL can be used to directly access the file via HTTP.
                  const publicUrl = ('https://storage.googleapis.com/'+ bucket.name + '/' + blob.name)
                  res.status(200).send(publicUrl);
              });
              
              blobStream.end(req.file.buffer)//req.file is your original file
              

              【讨论】:

              • 请注意,multer.singlediskStorage 将给出一个未定义的缓冲区,您需要从文件中读取它。否则,你会在 GCS 中得到一个 0B 文件。
              【解决方案7】:

              要在 .NET Core 的特定目录中上传,请使用

              var uploadResponse= await storageClient.UploadObjectAsync(bucketName, $"{foldername}/"+fileName, null, memoryStream);
              

              这应该将您的文件“fileName”上传到存储桶中的文件夹“foldername”中

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2015-09-09
                • 1970-01-01
                • 1970-01-01
                • 2015-12-06
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多