Skip to content Skip to sidebar Skip to footer

Converting Byte Array Output Into Blob Corrupts File

I am using the Office Javascript API to write an Add-in for Word using Angular. I want to retrieve the Word document through the API, then convert it to a file and upload it via PO

Solution 1:

I ended up doing this with the fileContent string:

let bytes = newUint8Array(fileContent.length);

for (let i = 0; i < bytes.length; i++) {
    bytes[i] = fileContent.charCodeAt(i);
}

I then proceed to build the Blob with these bytes:

let blob = new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });

If I then send this via a POST request, the file isn't mangled and can be opened correctly by Word.

I still get the feeling this can be achieved with less hassle / less steps. If anyone has a better solution, I'd be very interested to learn.

Solution 2:

Pff! what is wrong with a getting a instance of File and not using FileReader api? c'mon Microsoft!

You should take the byte array and throw it into the blob constructor, turning a binary blob to string in javascript is a bad idea that can lead to "out of range" error or incorrect encoding

just do something along with this

var byteArray = newUint8Array(3)
byteArray[0] = 97
byteArray[1] = 98
byteArray[2] = 99newBlob([byteArray])

if the chunk is an instance of a typed arrays or a instance of blob/file. in that case you can just do:

blob=newBlob([blob, chunk])

And please... don't base64 encode it (~3x larger + slower)

Solution 3:

thx for your answer, Uint8Array was the solution. Just a little improvement, to avoid creating the string:

let bytes = newUint8Array(docdata.length);
for (var i = 0; i < docdata.length; i++) {
    bytes[i] = docdata[i];
}

Post a Comment for "Converting Byte Array Output Into Blob Corrupts File"