Home > other >  How to convert byte array to blob in javascript for angular?
How to convert byte array to blob in javascript for angular?

Time:11-24

I am getting excel file from backend in the form of byte array. I want to convert that byte array into blob and then into file type. Please take a look at following code which i have used.

this.getFile().subscribe((response)=>{
const.byteArray=new Uint8Array(atob(response.data).split('').map(char)=>char.charCodeAt(0))
this.pdfResult=new(Blob[byteArray],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
let file=new File([this.pdfResult],"sample.xlsx")
});

CodePudding user response:

If you have got byte array correctly this function may help getting type properly

  function(ext) {
        if (ext != undefined) {
            return this.extToMimes(ext);
        }
        return undefined;
    }

extToMimes(ext) {
        let type = undefined;
        switch (ext) {
            case 'jpg':
            case 'png':
            case 'jpeg':
                type = 'image/jpeg'
                break;
            case 'txt':
                type = 'text/plain'
                break;
            case 'xls':
                type = 'application/vnd.ms-excel'
                break;
            case 'doc':
                type = 'application/msword'
                break;
            case 'xlsx':
                type = 'application/vnd.ms-excel'
                break;
            default:

        }
        return type;
    }


let _type = this.function(fileExtension.toLowerCase());
const blob = new Blob([byteArray], { type: _type });
let file=new File([this.pdfResult],"sample.xlsx")



                          
  • Related