简体   繁体   中英

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.

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!

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",
});

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