我不熟悉上传到Google Cloud Bucket,并且在将pdf文档上传到Google Cloud Bucket时遇到问题。目的是使用PDFKit创建pdf文档,将其发送到Bucket,然后响应文件的URL,然后将其用于客户端以下载文件。
当前,文件正在上传到存储桶中,但是说它在尝试打开文件时已损坏,从前端下载的文件也是如此。
这是我目前拥有的创建方法:
const PDFDocument = require('pdfkit');
const storage = require('./storage');
async function create(req, res) {
const doc_name = `invoice_${req.body.id}.pdf`;
const doc = new PDFDocument({
compress: false,
});
doc.fontSize(12);
doc.text('PDFKit is simple', 10, 30, {
align: 'center',
width: 200,
});
doc.end();
const fileId = await storage.upload(doc, req.account.id);
const url = await storage.getSignedURL(fileId, doc_name);
res.send(JSON.stringify({ doc: { url: url[0], name: doc_name } }));
}
module.exports = create;
使用以下内容上传文件:
const { Storage } = require('@google-cloud/storage');
const moment = require('moment');
const stream = require('stream');
const uuidv4 = require('uuid/v4');
const storage = new Storage();
const bucket = storage.bucket(process.env.GOOGLE_STORAGE_BUCKET);
const fileSuffix = 'pdf';
const getBucketFile = fileName => bucket.file(`${fileName}.${fileSuffix}`);
const getSignedURL = (fileName, name) => {
const file = getBucketFile(fileName);
const config = {
action: 'read',
expires: moment()
.add(6, 'd')
.format('MM-DD-YYYY'),
responseDisposition: `inline; filename=${name}`,
};
return file.getSignedUrl(config);
};
const upload = (data, prefix) => new Promise((resolve, reject) => {
const uuid = `${prefix}/${uuidv4()}`;
const stream = require('stream');
const bufferStream = new stream.PassThrough();
bufferStream.end(Buffer.from(data.toString(), 'base64'));
const file = getBucketFile(uuid);
bufferStream
.pipe(file.createWriteStream())
.on('error', err => reject(err))
.on('finish', () => resolve(uuid));
});
module.exports = {
getSignedURL,
upload,
};
我曾经见过其他人使用Firebase,但正在努力转换为Google Cloud。任何帮助将不胜感激!
答案 0 :(得分:1)
我已将您上传到适合我的版本:
const { Storage } = require("@google-cloud/storage");
const { v4: uuidv4 } = require("uuid");
const bucketName = require("../config/endpoints").BUCKETNAME;
const storage = new Storage();
const bucket = storage.bucket(bucketName);
const fileSuffix = "pdf";
const getBucketFile = fileName =>
bucket.file(`${fileName}.${fileSuffix}`);
const getSignedURL = async fileName => {
let validTime = new Date();
validTime.setHours(validTime.getHours() + 1);
const config = {
version: "v4",
action: "read",
expires: validTime
};
const signedUrl = await storage
.bucket(bucketName)
.file(fileName)
.getSignedUrl(config);
return signedUrl;
};
const upload = (data) =>
new Promise((resolve, reject) => {
const uuid = `pdf/${uuidv4()}`;
const file = getBucketFile(uuid);
const stream = file.createWriteStream({
metadata: {
"Content-Type": "application/pdf",
"content-Disposition": `attachment; filename=${uuid}.pdf`
},
resumable: false
});
stream.on("error", err => {
reject(error);
});
stream.on("finish", () => {
resolve(uuid);
});
stream.end(Buffer.from(data.toString(), "binary"));
});