I'm having problems downloading a .docx file from server. I can correctly upload and download pdf files or txt files, but not docx files.
When uploading I do this in my onNativeInputFileSelect method:
if(event.target.value){
const file: File = event.target.files[0];
let fileToUpload = new MyFile();
let filenames = file.name.split('.');
fileToUpload.name= filenames[0];
fileToUpload.type = filenames[1];
this.changeFile(file).then((base64: string):any => {
fileToUpload.content= base64;
this.networkService.uploadFileDocumento(fileToUpload).subscribe(() => {
...
where changeFile is this method:
changeFile(file){
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
When I upload a pdf file, the base64string starts with
data:application/pdf;base64,JVBERi0xLjUKJb/3ov...
and when I upload the docx file the base64string starts with
data:application/octet-stream;base64,UEsDBB...
Then I try to download the files. I can correctly download the pdf file, but when I try to download the docx file I don't get the correct file type (the type of file is "File") and I can't open it as a document. When I get the file from the server I do this:
let splitted = file.content.split(',');
let type = splitted[0].substring(splitted[0].lastIndexOf(':') +1, splitted[0].lastIndexOf(';'));
let blob = this.b64toBlob(splitted[1], type);
let blobUrl = URL.createObjectURL(blob);
let doc = document.createElement("a");
doc.href = blobUrl;
doc.download = file.name;
doc.click();
Where b64toBlob is the following method:
b64toBlob(b64Data, contentType = '', sliceSize = 512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
Why do I get application/octet-stream when uploading the file? And then I can't download id with the correct type? Where am I going wrong?