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:
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.
Using this
base64String.replace(/^data:.+;base64,/, "")
instead of
base64String.replace(/^data:image\/(png|gif|jpeg|jpg|pdf);base64,/, "")
works.