谷歌云功能下载文件并重定向到存储桶

时间:2017-11-17 21:29:42

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

我正在尝试在Node.js中使用google云功能下载wordpress repo的文件,然后将文件发送到google云端桶。我有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}';

}

2 个答案:

答案 0 :(得分:2)

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

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

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

您可以看一下我的sample function here

答案 1 :(得分: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();
};