I get a byte[]
file from my server with the content of a file. I know the name and the content-type
. So far I have tried the following for downloading the file:
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const file = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = "test.txt";
a.click();
window.URL.revokeObjectURL(url);
But this solution just downloads a text file with the binary content in it. How can I convert the binary data to the correspondent file type in the client side using JavaScript/Typescript? Thanks!
I get a byte[]
file from my server with the content of a file. I know the name and the content-type
. So far I have tried the following for downloading the file:
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const file = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = "test.txt";
a.click();
window.URL.revokeObjectURL(url);
But this solution just downloads a text file with the binary content in it. How can I convert the binary data to the correspondent file type in the client side using JavaScript/Typescript? Thanks!
Share Improve this question edited Jun 10, 2022 at 10:23 Iñigo asked Jul 17, 2019 at 11:33 IñigoIñigo 2,01610 gold badges31 silver badges60 bronze badges3 Answers
Reset to default 11You can use file-saver
import { saveAs } from 'file-saver';
const file = new Blob([content], {type: 'text/plain'});
FileSaver.saveAs(file, "test.txt");
saveByteArray(bytes, type) {
var blob = new Blob([bytes],{type:type});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "fileName";
link.click();
}
c#.net:
public byte[] DocContent { get; set; }
Angular:
DocContent:ArrayBuffer;
typescript:
var content= this.base64ToArrayBuffer(response.DocContent);
var blob = new Blob([content], { type: response.ContentType });
base64ToArrayBuffer(base64: any): ArrayBuffer {
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;
}