This question already has answers here:
ie11 Downloading Base64 documents
(4 answers)
Closed 4 years ago.
I am trying to download base64 data using “window.location.href” in JavaScript. It works fine in Chrome but the same code is not working in IE11.
Could you please let me know the fix or a workaround for the same?
Here is the code:
Javascript:
function DownloadPdf() {
window.location.href = "data:application/pdf;base64,JVBERi0xLjMNJeLjz9MNCj........Pg1zdGFydHhyZWYNMTczDSUlRU9GDQ=="
}
function DownloadExcel() {
window.location.href = "data:application/vnd.ms-excel;base64,UEsDBBQABgAIAAAAIQB......BLBQYAAAAACgAKAIACAACzHAAAAAA="
}
HTML:
NOTE:
I am developing an offline website where I am storing file in browser localStorage in base64 string format which is not connected to server. I don’t have any physical file present.
Below is working for me in all browsers
var blob = new Blob([tdData], { type: 'text/csv' });
if (window.navigator.msSaveBlob) { // // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveOrOpenBlob(blob, 'exportData' + new Date().toDateString() + '.csv');
}
else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, { type: "text/plain" });
a.download = "exportData" + new Date().toDateString() + ".csv";
document.body.appendChild(a);
a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}
I have found a plugin for javascript which may be usefull for you in this case, it is developed to download the base64 content with MIME types specified .
Moreover
Please have a look at this answer which explains how to download the base64 encoded content .
function fnExport(base64encodedstring) {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
// If Internet Explorer:
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
txtArea1.document.open("content type", "replace");
txtArea1.document.write(base64encodedstring);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, reportname + ".extension");
console.log(sa);
}
else { //other browser not tested on IE 11
sa = window.open('data:content-type;base64,' +base64encodedstring);
}
return (sa);
}
Follow these steps to download a Word document from .NET Web API to ajax.
Convert a file to base64 format (this is just 2 lines of code in C#)
Return base64 string to front end.
Convert base64 string to blob using below function.
base64toBlob = function (base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
//var byteCharacters = decodeURIComponent(escape(window.atob(base64Data)))
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Render blob as a file. This has to be handled slightly differently in Chrome vs IE. For Chrome, we need to use link download option.
Please refer to this link for IE 11:
https://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Related
I am getting the response from rest api as:
<Response>
<PDFContent>SlZCRVJpMHhMalFLSmVMano5TUtNU0F3SUc5aWFnbzhQQzlUTDBwaGRtRlRZM0pwY0hRdlNsTW9kR2hwY3k1NmIyOXRJRDBnTVRBd095aytQZ3BsYm1Sdlltb0tOU0F3SUc5aWFnbzhQQzlEYjJ4dmNsTndZV05sTDBSbGRtbGpaVWR5WVhrdlUzVmlkSGx3WlM5SmJXRm5aUzlJWldsbmFIUWdNVFV3TDBacGJIUmxjaTlHYkdGMFpVUmxZMjlrWlM5VWVYQmxMMWhQWW1wbFkzUXZWMmxrZEdnZ056Y3lMMHhsYm1kMGFDQTNNek0zTDBKcGRITlV3cjFTdkgvd0JvNy9rbm1uLzloV1AvQU5GUzBBZUFmOEozNHcvNkd2WFAvQmpOL3dERlVmOEFDZCtNUCtocXhycFg5L2V5ZlRZRURvYTRmdUNBNWNDQjFVSjJEd005cWwyZE9LbzlOSDVhVXdkdjVTVFRYbkMwVWVZbnlyVE5N6bnRLaXRSWHV1REUxUHNSL2lGQ2FpdGhvTUlacGQ0NmxMU0d3aVdZSkZoVVVaRm5KbnN5NHpPWE9BZS94ZDEIyOTBJREl6SURBZ1VpOVRhWHBsSURJMVBqNEtjM1JoY25SNGNtVm1DakUzT1RjMU5Rb2xKVVZQUmdvPQ==</PDFContent>
<Success>True</Success>
</Response>
How to get the response inside and generate pdf using React js
you can simply add in object tab in reactjs
<div>
<object
style={{width: '100%', height: '200pt'}}
type="application/pdf"
data={'data:application/pdf;base64,'+base64data}></object>
</div>
I am assuming the bytes within <PDFContent> tag are base64 encoded bytes of the PDF file. If this is incorrect, you need to update your REST API to perform base64 encoding on the PDF bytes first. You can't have your server send raw PDF bytes to the web client as is.
In the javascript, once you have received the base64 encoded PDF bytes, you can generate the PDF in two steps:
Convert the base64 encoded bytes to a PDF BLOB.
Create a file URL out of this BLOB and open the URL.
Here's a sample JavaScript code for the same:
<script>
function displayPDF() {
//The PDFContent bytes are mapped to an input element called pdfString
if($('#pdfString').val() == '')
return;
var file = b64toBlob($('#pdfString').val(), 'application/pdf');
//If the browser is IE or Edge
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
}
else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
</script>
I'm trying to pass a PDF file from the server and display it inside the browser, but the output comes out corrupted.
var blob = atob(data.Package);
console.log(blob);
var file = new Blob([blob], { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
Console log outputs something that appears to be correct PDF (just the beginning of output):
I'm saving a copy of the PDF on the server before transfer to make sure it is not corrupt and it works.
URL constructed with URL.createObjectURL(file) seems to be short:
blob:http://localhost:61631/ad749684-2992-4311-8b17-f382a7c687be
server side code:
Object doc = Convert.ToBase64String(_Document.DocumentStream.ToArray());
JObject response = new JObject(new JProperty("Package", JObject.FromObject(doc)));
return new AspResponse<Object>(response);
It looks like the issue is because you need to convert the PDF data into an actual byte array, then pass that into the Blob constructor. Try this:
function convertToByteArray(input) {
var sliceSize = 512;
var bytes = [];
for (var offset = 0; offset < input.length; offset += sliceSize) {
var slice = input.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
bytes.push(byteArray);
}
return bytes;
}
var blob = atob(data.Package);
console.log(blob);
var file = new Blob(convertToByteArray(blob), { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
This solution worked for me, basically generating the pdf as a base64 string in the backend and rendering the content in an anchor tag for downloading the pdf file.
https://kainikhil.medium.com/nodejs-how-to-generate-and-properly-serve-pdf-6835737d118e
I have looked at quite a few samples of how people are getting their base 64 byte arrays into PDF but sadly none seem to be working for me. Looked at :
Javascript: Open PDF in new tab from byte array and how to convert byte array to pdf and download
my code is not really any different from what I can tell.
I have a JS-Fiddle here with test byte array data that I can confirm via different base64 encoders/decoders that it is valid.
I am hoping someone can see what I am doing wrong with it. I am using the atob() wrapper to decode the base64 string and it does appear to be doing it correctly. Thanks to anyone who has suggestions.
For those who would prefer to just look at it here:
function go() {
var data = byteData ;
// console.log(data);
var pdfData = atob(data);
console.log(pdfData)
var file = new Blob([pdfData], {type:'application/pdf'});
var fileUrl = URL.createObjectURL(file);
//open it via a link
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.href = fileUrl;
a.download = fileName;
a.click();
//open it directly
window.open(fileUrl);
}
const byteData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PC9yZGY6U2VxPgogICAgICAgICA8L2RjOmNyZWF0b3I+CiAgICAgICAgIDx4bXBNTTpEb2N1bWVudElEPnV1aWQ6OTg1OWJhYTMtNTI1ZS00MjA3LTljNWUtN2IxMGVmYmM2NzRmPC94bXBNTTpEb2N1bWVudElEPgogICAgICAgICA8eG1wTU06SW5zdGFuY2VJRD51dWlkOjIwNzU1NmJjLTBmMWUtNGNhYS1iNWJhLWUwNzAwZTY5Yzc2MjwveG1wTU06SW5zdGFuY2VJRD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/Pg0KZW5kc3RyZWFtDWVuZG9iag0zIDAgb2JqDTw8L0ZpbHRlci9GbGF0ZURlY29kZS9GaXJzdCA0L0xlbmd0aCA0OS9OIDEvVHlwZS9PYmpTdG0+PnN0cmVhbQ0KaN6yUDBQsLHRd84vzStRMNT3zkwpjjY0AgoGxeqHVBak6gckpqcW29kBBBgA3/oLrQ0KZW5kc3RyZWFtDWVuZG9iag00IDAgb2JqDTw8L0ZpbHRlci9GbGF0ZURlY29kZS9GaXJzdCA0L0xlbmd0aCAxNTMvTiAxL1R5cGUvT2JqU3RtPj5zdHJlYW0NCmjefMy9CoMwFEDhV7mbydD8WKVaRJBmFYSWdnGxyQUDwZRrxNevQ+fu5zs1KGga2W1pjsT63hoMgcsb4ZR8XMyUkJlrrnSlKn3Wha6L4qQumVLZrzrYcLfkP6kULgR4Iq2HhFLkIueyj+7/ZKDoNovEOkvxPSUwfk0+BCTQpVAwspdfXNzXkXP58CkgW3AHzdv2K8AAYHM3rA0KZW5kc3RyZWFtDWVuZG9iag01IDAgb2JqDTw8L0RlY29kZVBhcm1zPDwvQ29sdW1ucyA0L1ByZWRpY3RvciAxMj4+L0ZpbHRlci9GbGF0ZURlY29kZS9JRFs8MkQyMkNBQUM5MjQxOEE3Qjg3RkMxODU3NzVGNzAwMzQ+PEZENDkxMzFBNDA0MjM4NEI5NjMxRjRBRjdENDQxQjYwPl0vSW5mbyA5IDAgUi9MZW5ndGggNDgvUm9vdCAxMSAwIFIvU2l6ZSAxMC9UeXBlL1hSZWYvV1sxIDIgMV0+PnN0cmVhbQ0KaN5iYgACJkauCwxMDIxtQIK3HcTqBRHfgBLPFgJZDAyMQILpP5BgZAAIMACRngYbDQplbmRzdHJlYW0NZW5kb2JqDXN0YXJ0eHJlZg0KMTE2DQolJUVPRg0K";
you also need to convert your base64 string to arraybuffer.
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
from this convert base64 string to arraybuffer
and call it in your code sample like this :-
function go() {
var data = byteData ;
// console.log(data);
// HERE THIS CHANGE IN YOUR CODE
var pdfData = _base64ToArrayBuffer(data);
var file = new Blob([pdfData], {type:'application/pdf'});
var fileUrl = URL.createObjectURL(file);
//open it via a link
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.href = fileUrl;
a.download = fileName;
a.click();
//open it directly
window.open(fileUrl);
}
this jsfiddle :- fiddle
There must be a way to do this more efficiently. What I'm doing is conceptually very simple:
1) Call a web service and receive b64-encoded-string of a PDF blob.
2) Decode it, create blob, render PDF in new window. Account for pop-up blocker.
My code works. Nothing fancy. Its all client-side. Everything works but IE runs SUPER slow compared to the other browsers (IE 11 vs. current Chrome/Firefox/Safari).
In light of this I am certain I could do this more efficiently. Any tips on how to speed this up for IE 11?
Note: I'm using Jeremy's b64toBlob function (thanks Jeremy).
Part I: modal stuff
var box = new SimpleDialog(Dialogs.getNextId(), false);
box.title = "Fetching PDF";
box.isMovable = false;
box.extraClass = "";
box.width = 400;
box.isModal = true;
box.createDialog();
window.parent.box = box;
box.setContentInnerHTML('<p>Please wait....</p>');
box.show();
Part II: call external service, receive b64 encoded string
setTimeout(function(){
var response = ... ; //do callout... get data
var statusCode = ...; //parse from response
var b64Data = ... ; //parse from response
if(statusCode == 200) {
//Account for IE
if (navigator.appVersion.toString().indexOf('.NET') > 0) {
var blob = b64toBlob(b64Data, "application/pdf");
var fileURL = URL.createObjectURL(blob);
window.navigator.msSaveOrOpenBlob(blob, "theFile.pdf");
window.parent.box.cancel();
} else {
var blob = b64toBlob(b64Data, "application/pdf");
var fileURL = URL.createObjectURL(blob);
var pdfWin = window.open(fileURL,"_blank","width=1000,height=800");
if(!pdfWin) {
box.setTitle("Success: PDF has been retrieved");
box.setContentInnerHTML("<p align='left'></p><p align='left'>A popup blocker was detected. The PDF will not open automatically.<br /><br /></p><p align='left'><a onclick='window.parent.box.cancel();' target='_blank' href='"+fileURL +"' >Click here to view .pdf</a><br /><br /></p><p align='center'><button class='btn' onclick='window.parent.box.cancel(); return false;'>Cancel</button></p>");
} else {
window.parent.box.cancel();
}
}
} else {
box.setTitle("Error fetching PDF");
box.setContentInnerHTML("<p align='left'><img src='/img/msg_icons/warning32.png' style='margin:0 5px;'/></p><p align='left'>Unable to retrieve PDF.</p><p align='center'><button class='btn' onclick='window.parent.box.cancel(); return false;'>OK</button></p>");
}
},200);
I don't really see any slowness, and this plunkr run in IE, (using an update on the original "Jeremy" solution) works just fine:
Sample pdf
There was an update in the original post that improves the answer further:
function base64toBlob(base64Data, contentType, sliceSize) {
var byteCharacters,
byteArray,
byteNumbers,
blobData,
blob;
contentType = contentType || '';
byteCharacters = atob(base64Data);
// Get blob data sliced or not
blobData = sliceSize ? getBlobDataSliced() : getBlobDataAtOnce();
blob = new Blob(blobData, { type: contentType });
return blob;
/*
* Get blob data in one slice.
* => Fast in IE on new Blob(...)
*/
function getBlobDataAtOnce() {
byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
return [byteArray];
}
/*
* Get blob data in multiple slices.
* => Slow in IE on new Blob(...)
*/
function getBlobDataSliced() {
var slice,
byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
slice = byteCharacters.slice(offset, offset + sliceSize);
byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
// Add slice
byteArrays.push(byteArray);
}
return byteArrays;
}
}
From the answer here:
martinoss answer
Is the plunkr slow for you? Can you put in some logging to understand which call is actually slow? Put in a timer and log each line. on the IE route. Which one is reporting "slowness"?
Update On the plunkr, I've put a very simple timer, it shows that there is just 46ms approx taken to get the PDF to you in IE11. Obviously it's not multithreaded, but it is an indication.
I'm using flash to capture audio, encode it to mp3, then send it to javascript as ByteArray.
Now I want the javascript to save it as MP3 on my computer (not flash saves it to my computer). I am using Blob and then getDataURL, but the file isn't playing when saved. I used to do the same exact method to save WAV files and it worked perfectly fine.
Here's the JS code:
var getDataFromSWF = function (bytes) {
var myBlob = new Blob([bytes], { type: "audio/mpeg3" });
var url = (window.URL || window.webkitURL).createObjectURL(myBlob);
var link = window.document.createElement('a');
link.href = url;
// $("label").text(url);
link.download = 'output.mp3';
var click = document.createEvent("Event");
click.initEvent("click", true, true);
link.dispatchEvent(click);
// console.log(bytes);
}
I'm pretty much sure that the byteArray is fine because if I let the SWF save the file it works OK too. But I want to know what's wrong with the JS code. (note: i'm new to BLOB)
Try this to get the Blob
function base64toBlob(base64Data, contentType) {
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}