在云功能中将文件从 URL 上传到 Google 存储 [英] Upload a file, from an URL to Google Storage, in a cloud function

查看:19
本文介绍了在云功能中将文件从 URL 上传到 Google 存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to find a way to upload a PDF file, generated by a php/MySQL server to my Google Storage bucket. The URL is simple : www.my_domain.com/file.pdf . I tried with the code below , but I'm having some issues to make it work. The error is : path (fs.createWriteStream(destination)) must be a string or Buffer. Thanks in advance for your help !

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

}

推荐答案

我终于找到了解决方案:

I finally found a solution :

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

}

这篇关于在云功能中将文件从 URL 上传到 Google 存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆