【问题标题】:Google cloud function download file and redirect to bucket storage谷歌云功能下载文件并重定向到桶存储
【发布时间】:2018-05-01 18:10:05
【问题描述】:

我正在尝试使用 Node.js 中的谷歌云功能来下载 wordpress 存储库的文件,然后将文件发送到谷歌云存储桶中。我下载了 wordpress 文件,但它无法写入谷歌存储桶。

function writeToBucket(jsonObject){

/*
 *  Google API authentication
 */

var gcs = require('@google-cloud/storage')({
         projectId: 'wp-media-cdn',
         keyFilename: 'wp-media-cdn-d9d7c61bfad9.json'
});

/*
 *  rename image file with image size, format: size X size imgName
 */

var pluginUrl = "https://downloads.wordpress.org/plugin/bbpress.2.5.14.zip";
    newPluginName = "bbpress";

/*
 *  Read image into stream, upload image to bucket
 */

var request = require('request');
var fs = require('fs'); //used for createWriteString()

var myBucket = gcs.bucket('test_buckyy'); //PUT BUCKET NAME HERE
var file = myBucket.file(nnewPluginName);

// file.exists() returns true if file already in bucket, then returns file url, exits function
if(file.exists()){
    return 'https://storage.googleapis.com/${test_buckyy}/${file}';
}

//pipes image data into fileStream
var fileStream = myBucket.file(newImageName).createWriteStream();
request(imgUrl).pipe(fileStream)
    .on('error', function(err) {
        console.log('upload failed');
    })
    .on('finish', function() {
        console.log('file uploaded');
    });
/*
 *  return image url
 *  use getSignedUrl
 */


    return 'https://storage.googleapis.com/${test_buckyy}/${file}';

}

【问题讨论】:

  • 请发布错误消息。查看日志信息。
  • 您好,您找到解决方案了吗?如果是这样,你能补充一个答案吗?
  • 我能看到的唯一问题是newPluginName 的错字:var file = myBucket.file(nnewPluginName);

标签: node.js google-cloud-platform google-cloud-functions google-cloud-storage


【解决方案1】:

我刚刚复制了您的用例场景,并成功将文件下载到 Cloud Function 的临时文件夹中,然后我从那里将此文件复制到存储桶中。

为了实现这一点,我使用 createWriteStream 将文件下载到 /tmp 文件夹中,因为这是我们可以在云函数中存储文件的唯一文件夹,如 Cloud Functions Execution Environment 文档中所述。

之后,我只是按照Cloud Storage Uploading Objects 文档将文件复制到存储桶中。

你可以看看我的示例函数

Index.js

const {Storage} = require('@google-cloud/storage');

exports.writeToBucket = (req, res) => {
const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("/tmp/yourfile.jpg");
const request = http.get("YOUR_URL_TO_DOWNLOAD_A_FILE", function(response) {
  response.pipe(file);
});

console.log('file downloaded');

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

// Creates a client
const storage = new Storage();
const bucketName = 'YOUR_BUCKET_NAME';
const filename = '/tmp/yourfile.jpg';

// Uploads a local file to the bucket
storage.bucket(bucketName).upload(filename, {
  gzip: true,
  metadata: {
    cacheControl: 'no-cache',
  },
});

res.status(200).send(`${filename} uploaded to ${bucketName}.`);

};


package.json

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
        "@google-cloud/storage": "^3.0.3"
    }
}

【讨论】:

    【解决方案2】:

    使用Chris32 的回答我创建了一个类似的版本,但避免将图像下载到 tmp 文件夹。希望有用!

    'use strict';
    
    const http = require('http');
    const {Storage} = require('@google-cloud/storage');
    
    exports.http = (request, response) => {
      const imageUrl = request.body.url;
      const fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
    
      const storage = new Storage({keyFilename: "keyfile.json"});
      const bucket = storage.bucket('MY_BUCKET_NAME');
      const file = bucket.file(fileName);
    
      console.log('Uploading image')
      http.get(imageUrl, function(res) {
        res.pipe(
          file.createWriteStream({
            resumable: false,
            public: true,
            metadata: {
              contentType: res.headers["content-type"]
            }
          })
        );
      });
    
      console.log('Image uploaded')
      response.status(201).send('Image successful uploaded!');
    };
    
    exports.event = (event, callback) => {
      callback();
    };
    

    【讨论】:

    • 正是我需要的!我在下载和上传时遇到了一些图像编码问题
    • @Maximilliano De Lorenzo 您使用的http 包是什么?它在 npm 上不存在:npmjs.com/package/http
    • 我们能不能把 http 换成 sindresorhus 的 got 这样的包?
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2019-02-09
    • 2021-08-10
    • 2021-08-21
    • 2020-06-01
    • 2017-06-11
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多