简体   繁体   中英

Encoding PDF to Base64 string and using Node.js Buffer.from() results in broken file

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM