Home > Software engineering >  Download xml file angular by response from web api c#
Download xml file angular by response from web api c#

Time:06-04

I want to download xml file from database. Web api (C#) return file in byte[]. How can I read this bytes and convert it to xml file from client site (Angular)? I tried blob and other things but when I open downloaded xml file there is strange text like this:

"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxYdHJhUmVwb3J0c0xheW91dFNlcmlhbGl6ZXIgU2VyaWFsaXplclZlcnNpb249IjIwLjIuNC4wIiBSZWY9". 

But I want to get xml file like this:

<?xml version="1.0" encoding="utf-8"?>
...

My code in Angular:

getExportData(id: string): Observable<any> {
    const url = this.buildUrl('/ExportToXML/'   id);
    return this.http.get(url, { responseType: 'blob' });
}
this.service.getExportData(item.Id)
    .subscribe((response) => {
        const element = document.createElement('a');
        const blob = new Blob([response], { type: 'text/xml' });
        const url = URL.createObjectURL(blob);
        element.href = url;
        element.setAttribute('download', 'acl.xml');
        document.body.appendChild(element);
        element.click();
    }, error => {
        console.log(error);
    });

Please help me as soon as possible. Thanks :-)

CodePudding user response:

The string is being returned in base64 format. You need to decode it from base64. When I decode the sample string you provided, I get

<?xml version="1.0" encoding="utf-8"?><XtraReportsLayoutSerializer SerializerVersion="20.2.4.0" Ref=

You can use the atob() javascript function to decode the data.

var decoded = atob("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxYdHJhUmVwb3J0c0xheW91dFNlcmlhbGl6ZXIgU2VyaWFsaXplclZlcnNpb249IjIwLjIuNC4wIiBSZWY9");
console.log(decoded);
  • Related