1

I have a frontend where users can upload documents (PDFs). It converts these PDFs to a Base64 string and then sends it to a microservice where it is uploaded to Backblaze B2. This method works fine when uploading e.g. a .jpg file, but when trying it with a .pdf file it doesn't let me open it when browsing files on Backblaze's website:

enter image description here

So here is my frontend code:

export const toBase64 = (file: File | Blob) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });

...

const base64String = await toBase64(acceptedFiles[index]);
onSelectFile(base64String as string);

and here is my backend code:

const { base64String, fileName } = request.body.input;

const fileBuffer = Buffer.from(
  base64String.replace(/^data:image\/(png|gif|jpeg|jpg|pdf);base64,/, ""),
  "base64"
);

const getUploadUrlResponse = await b2.getUploadUrl({
  bucketId: process.env.BACKBLAZE_BUCKET_ID || "bucketId",
});

const uploadFileResponse = await b2.uploadFile({
  uploadUrl: getUploadUrlResponse.data.uploadUrl,
  uploadAuthToken: getUploadUrlResponse.data.authorizationToken,
  fileName: fileName,
  data: fileBuffer,
  mime: "application/pdf",
});

As I said, this works fine when uploading a .jpg, but results in "failed to load PDF document" when using a .pdf. I am not sure what I am doing wrong or how to fix this.

1
  • 1
    Isn't pdf's mimetype application/pdf? Your .replace() is trying to replace image/pdf. I'm surprised .from() isn't throwing an exception on that. Commented Nov 19, 2020 at 9:26

1 Answer 1

1

Using this

base64String.replace(/^data:.+;base64,/, "")

instead of

base64String.replace(/^data:image\/(png|gif|jpeg|jpg|pdf);base64,/, "")

works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.