I am writing frontend Angular application, where user should be able to upload MS Word template files (.dotx) and later download them on demand. Due to file size limitations I have to upload files as byte array and files will be stored and downloaded in this format. Approach, described below works fine with .txt files, however with MS Word files it does not work. Downloaded MS Word file has issues with encoding and is not readable. Part 1: Uploading file I use to get file from user:
<input type="file" class="file-input" (change)="onFileSelected($event)">
Reading file to byte array ("uploading file"):
onFileSelected($event) {
const file = $event.target.files[0] as File;
const reader = new FileReader();
const fileByteArray = [];
reader.readAsArrayBuffer(file);
reader.onloadend = (evt) => {
if (evt.target.readyState === FileReader.DONE) {
const arrayBuffer = evt.target.result as ArrayBuffer;
const array = new Uint8Array(arrayBuffer);
for (const a of array) {
fileByteArray.push(a);
}
this.byteArray = fileByteArray;
}
};
}
Downloading file:
downloadFile() {
const bytesView = new Uint8Array(this.byteArray);
const str = new TextDecoder('windows-1252').decode(bytesView); //windows-1252 encoding used here for cirilic
const file = new Blob([str], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'});
saveAs(file, 'test.dotx');
}
Did not find similar issues in Internet, I guess it is not standard way of dealing with files. Is it ever possible to process MS Word files as byte array with JS?
Another important question - is it safe to upload a file as an array of bytes, saved in database?
Appreciate any help.