我尝试找到一种将php / MySQL服务器生成的PDF文件上传到我的Google存储桶的方法。 URL很简单:www.my_domain.com/file.pdf。我尝试使用下面的代码,但是遇到一些问题使其无法正常工作。错误为:路径(fs.createWriteStream(destination))必须为字符串或Buffer。预先感谢您的帮助!
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();
});
});
}
答案 0 :(得分: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();
});
}
});
}
答案 1 :(得分:0)
firebase-admin自v7.0.0起使用google-cloud/storage v2.3.0
,can no longer accept file URLs位于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();
});