firebase 在云功能中将文件从URL上传到Google Storage

7lrncoxx  于 2022-11-17  发布在  Go
关注(0)|答案(2)|浏览(170)

我试着找到一种方法来上传一个由php/MySQL服务器生成的PDF文件到我的Google存储桶。www.my_domain.com/file.pdf。我尝试使用下面的代码,但遇到了一些问题,无法正常工作。错误是:path(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();
        });
    });

}
wmvff8tz

wmvff8tz1#

我终于找到了解决办法:

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();
            });
        }
    });

}
nuypyhwy

nuypyhwy2#

从v7.0.0开始,firebase管理员使用google-cloud/storage v2.3.0,即bucket.upload上的can no longer accept file URLs
我想我也会分享我的解决方案。

const rq = require('request');

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

const 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();
});

相关问题