Home > OS >  Saving a Base64-encoded PDF string to firebase storage using firebase-admin in a cloud function
Saving a Base64-encoded PDF string to firebase storage using firebase-admin in a cloud function

Time:01-27

I have the contents of a PDF file encoded in a base-64 string that I would like to save to Firebase Storage using the Firebase Admin SDK in a TypeScript cloud function. Here is what I am trying:

const base64Pdf = ...;
const file = admin.storage().bucket().file("invoices/642d5000-851f-449d-8c4a-ec49aafabf80.pdf");
const pdfBuffer = Buffer.from(base64Pdf, "base64");
try {
  await file.setMetadata({
    contentType: "application/pdf",
  });
  await file.save(pdfBuffer);
  const signedUrls = await file.getSignedUrl({
    action: "read",
    expires: "12-31-2500",
  });
  ...
} catch (e) {
  functions.logger.error(`[checkDocuments] Error saving PDF: ${e}`);
}

But I keep getting an error saying that the file object does not exist. I know it does not exist, since I'm trying to create it:

Error saving PDF: Error: No such object: myproject.appspot.com/invoices/642d5000-851f-449d-8c4a-ec49aafabf80.pdf

Note that I already double-checked that Firebase storage was enabled for my project, and I even tried to create an "invoices" folder already.

CodePudding user response:

A file must exist before you can set its metadata. Try updating order of setMetadata() and save() as shown below:

// save file before setting metadata
await file.save(pdfBuffer);

await file.setMetadata({
  contentType: "application/pdf",
});

const signedUrls = await file.getSignedUrl({
  action: "read",
  expires: "12-31-2500",
});

Alternatively, you can set metadata using save() method itself:

await file.save(pdfBuffer, {
  metadata: {
    contentType: "application/pdf"
  },
});
  • Related