【问题标题】:Upload a file, from an URL to Google Storage, in a cloud function在云功能中将文件从 URL 上传到 Google 存储
【发布时间】:2019-02-06 17:23:16
【问题描述】:

我试图找到一种方法将由 php/MySQL 服务器生成的 PDF 文件上传到我的 Google 存储桶。 URL 很简单:www.my_domain.com/file.pdf。我尝试使用下面的代码,但我遇到了一些问题来使它工作。错误是:路径 (fs.createWriteStream(destination)) 必须是字符串或缓冲区。提前感谢您的帮助!

const http = require('http');
const fs = require('fs');
const {Storage} = require('@google-cloud/storage')
const gcs = new Storage({
    keyFilename: 'my_keyfile.json'
})
const bucket = gcs.bucket('my_bucket.appspot.com');
const destination = bucket.file('file.pdf');
var theURL = 'https://www.my_domain.com/file.pdf';

var download = function() {

    var file = fs.createWriteStream(destination);
    var request = http.get(theURL, function(response) {
        response.pipe(file);

        file.on('finish', function() {
            console.log("File uploaded to Storage")
            file.close();
        });
    });

}

【问题讨论】:

  • 您能否提供更多关于正在发生的事情的信息?你得到什么错误?问候。
  • 是的,抱歉,我正在编辑问题。错误是:错误是:路径必须是字符串或缓冲区。我找不到定位我的存储桶的方法。

标签: firebase google-cloud-storage google-cloud-functions


【解决方案1】:

我终于找到了解决办法:

const http = require('http');
const fs = require('fs');
const {Storage} = require('@google-cloud/storage')
const gcs = new Storage({
    keyFilename: 'my_keyfile.json'
})
const bucket = gcs.bucket('my_bucket.appspot.com');

const destination = os.tmpdir() + "/file.pdf";
const destinationStorage = path.join(os.tmpdir(), "file.pdf");

var theURL = 'https://www.my_domain.com/file.pdf';

var download = function () {

    var request = http.get(theURL, function (response) {
        if (response.statusCode === 200) {
            var file = fs.createWriteStream(destination);
            response.pipe(file);
            file.on('finish', function () {

                console.log('Pipe OK');

                bucket.upload(destinationStorage, {
                    destination: "file.pdf"
                }, (err, file) => {

                    console.log('File OK on Storage');
                });
                file.close();
            });
        }
    });

}

【讨论】:

  • 但是,如果我们直接上传文件而不存储到本地驱动器会更好
【解决方案2】:

从 v7.0.0 开始,firebase-admin 使用 google-cloud/storage v2.3.0can no longer accept file URLsbucket.upload 上。

我想我也会分享我的解决方案。

const rq = require('request');

// filePath = File location on google storage bucket
// fileUrl = URL of the remote file

let bucketFile = bucket.file(filePath);
const fileWriteStream = bucketFile.createWriteStream();
let rqPipe = rq(fileUrl).pipe(fileWriteStream);

// And if you want the file to be publicly readable
rqPipe.on('finish', async () => {
  await bucketFile.makePublic();
});

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 2017-12-21
    • 2021-10-28
    • 2017-05-04
    • 2021-03-07
    • 2018-11-17
    • 2021-04-21
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多