问题描述
我试图找到一种将php/MySQL服务器生成的PDF文件上传到我的Google存储桶的方法. URL很简单:www.my_domain.com/file.pdf.我尝试使用下面的代码,但是遇到一些问题使其无法正常工作.错误是:path(fs.createWriteStream(destination))必须是字符串或Buffer.预先感谢您的帮助!
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();
});
});
}
推荐答案
firebase-admin(从v7.0.0开始)使用google-cloud/storage v2.3.0
,其中不再接受bucket.upload
上的文件URL .
firebase-admin, as of v7.0.0, uses google-cloud/storage v2.3.0
, which can no longer accept file URLs on bucket.upload
.
我想我也将分享我的解决方案.
I figured I would share my solution as well.
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();
});
这篇关于通过云功能将文件从URL上载到Google Storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!