sachin kulkarni
sachin kulkarni

Reputation: 2848

File Download error:SyntaxError: Unexpected token M in JSON at position 0 Angular 11 HttpPost

I am getting above mentioned error while trying to download a file in angular 11. Status Code is 200 OK .Asp.Net Web Api is used to post file.

Below is the Code.

this.http.post<Blob>(url,{responseType: 'blob'}).subscribe({
    next: versionfiledata=>{
      return  versionfiledata;
    },
    error: error => {
      
      console.error('There was an error!', error);
    }
    
      } )

Error:SyntaxError: Unexpected token M in JSON at position 0

Not sure but I have tried using response type as blob but still getting the error using Angular 11

Upvotes: 0

Views: 1710

Answers (1)

sachin kulkarni
sachin kulkarni

Reputation: 2848

 const headers = { 'responseType': 'blob' as 'json'};
    const body = { title: 'Test' };
    return this.http.post<Blob>(url,body,headers).subscribe({next:response=>{
      console.log(response);
    var blob=new Blob([response],{type:"application/octet-stream"});
      FileSaver.saveAs(blob,file);

    }, error: error => {console.log("download error");}
  });

You need to change response in headers.

Upvotes: 1

Related Questions