João Santos
João Santos

Reputation: 125

Generating a File from a base64 string

I'm using a webservice to get a base64 string and I need to show that document to the user as a PDF.

var charactersArray = atob(base64String);
var byteNumbers = new ArrayBuffer(charactersArray.length);

for (var i = 0; i < charactersArray.length; i++) {
    byteNumbers[i] = charactersArray.charCodeAt(i);
}

var byteArray = new Uint8Array(byteNumbers);

var file = new File([byteArray], "file.pdf", {
    type: "application/pdf",
});

I'm then using this "file" to create a url with

var url = URL.createObjectURL(file);

I'm opening this url in a button with the ng-click directive, but I'm getting loading the PDF.

Upvotes: 0

Views: 165

Answers (2)

Steven B.
Steven B.

Reputation: 9362

You need to write the character codes to the byteArray rather than the ArrayBuffer

var charactersArray = atob(base64String);
var len = charactersArray.length;
var byteNumbers = new ArrayBuffer(len);

var byteArray = new Uint8Array(byteNumbers);

for (var i = 0; i < len; i++) {
    byteArray[i] = charactersArray.charCodeAt(i);
}

var file = new File([byteArray], "file.pdf", {
    type: "application/pdf",
});

Upvotes: 2

Jacob Vacheresse
Jacob Vacheresse

Reputation: 21

I recently work on a project like this and had the same issue. I used the base64-arraybuffer NPM library to convert a base64 string to a byte array.

It's a JS library so it needs to be imported like this after it's installed:

import * as buffer from 'base64-arraybuffer';

The object URL is created like this:

var byteArray = buffer.decode(base64String);
var file = new Blob([byteArray], {type: 'application/pdf'});
var pdfUrl = URL.createObjectURL(file);

I hope this helps!

Upvotes: 2

Related Questions