Firebase云函数-将文件对象上传到云存储

pinkon5k  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(218)

在我的函数中,我使用pdfkit库创建了一个pdf文件:

exports.getPdfUrl = functions.https.onRequest(async (req, res) => {
    const bucket = admin
        .storage()
        .bucket();
    //target file name
    const file = bucket
        .file('test.pdf');

    //creating the pdf file
    await new Promise<void>((resolve, reject) => {
        let stream = file.createWriteStream({
            resumable: false,
            contentType: "application/pdf",
        });
        stream.on("finish", () => resolve());
        stream.on("error", (e) => reject(e));
        const doc = new PDFDocument({ size: "A4", margin: 50 });
        doc.text("some text", 50, 50);
        doc.pipe(stream);
        doc.end();
    });
    ...

到目前为止,这是有效的,并创建了一个适当的pdf文件。
现在我想把创建的文件上传到存储器并返回一个url。

我不能这样做,因为getSignedUrl的最大过期时间是7天(我需要一个永久的URL):

const url = await file.getSignedUrl({
        version: "v4",
        action: "read",
        expires: Date.now() + 7 * 24 * 60 * 60 * 1000,
    });

我不能这样做,因为bucket.upload()的第一个参数是文件的路径,我没有,因为我只有File对象:

const [uploadedFile] = await bucket.upload('test.pdf', {
        destination: 'testNew.pdf',
        metadata: {
            contentType: 'application/pdf'
        }
    });
    await uploadedFile.makePublic();
    const publicUrl = `https://storage.googleapis.com/${bucket.name}/${encodeURIComponent('testNew.pdf')}`;
s5a0g9ez

s5a0g9ez1#

const tmpFilePath = path.join(os.tmpdir(), fileName);
    // Create a read stream from the Cloud Storage file
    const readStream = file.createReadStream();

    // Create a write stream to the local temporary file
    const writeStream = fs.createWriteStream(tmpFilePath);

    // Pipe the read stream to the write stream
    readStream.pipe(writeStream);

    // Listen for the finish event on the write stream
    await new Promise((resolve, reject) => {
        writeStream.on("finish", resolve);
        writeStream.on("error", reject);
    });

这将在存储桶的主目录中创建一个文件。
从那里可以将其保存到其他位置:

const [uploadedFile] = await bucket.upload(tmpFilePath, {
        destination: `someOtherPath/${fileName}`,
        metadata: {
            contentType: "application/pdf",
        },
    });
    await uploadedFile.makePublic();
    const url = `https://storage.googleapis.com/${bucket.name}/${encodeURIComponent(`someOtherPath/${fileName}`)}`;

相关问题