简体   繁体   English

从base64字符串生成文件

[英]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. 我正在使用Web服务获取base64字符串,并且需要将该文档以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. 我正在使用ng-click指令在一个按钮中打开此网址,但我正在加载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. 我使用base64-arraybuffer NPM库将base64字符串转换为字节数组。

It's a JS library so it needs to be imported like this after it's installed: 这是一个JS库,因此在安装后需要这样导入:

import * as buffer from 'base64-arraybuffer';

The object URL is created like this: 对象URL的创建如下:

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 您需要将字符代码写入byteArray而不是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",
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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