Загрузите файл с URL-адреса в Google Storage в облачной функции - PullRequest
0 голосов
/ 06 февраля 2019

Я пытаюсь найти способ загрузить файл PDF, созданный сервером php / MySQL, в мое хранилище Google Storage.URL-адрес прост: www.my_domain.com/file.pdf.Я попытался с кодом ниже, но у меня есть некоторые проблемы, чтобы заставить его работать.Ошибка: путь (fs.createWriteStream (пункт назначения)) должен быть строкой или буфером.Заранее спасибо за помощь!

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

}

Ответы [ 2 ]

0 голосов
/ 18 мая 2019

firebase-admin, начиная с v7.0.0, использует google-cloud/storage v2.3.0, который больше не может принимать файловые URL на bucket.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();
});
0 голосов
/ 06 февраля 2019

Я наконец нашел решение:

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

}
...