Zzz
Zzz

Reputation: 3025

Angular5 and Web Api - Download a PDF file

I am trying to download a pdf file from a call to a Web Api service in an Angular 5.2 application. The api call is returning 200 and appears to be returing the PDF doc correctly but I am receiving the folowing error:

SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad(...

It appears this error is being thrown by code that is intercepting the response as the .subscribe() method is never reached. I have tried both using application/pdf and application/octet-stream. I have looked at the following two stackoverflow questions but to no avail ( Question 1, Question 2).

Bellow is the code:

WebApi -

public HttpResponseMessage GetDocument(Guid orderDocumentGUID)
        {            
            TOrderDocument doc = _repository.OrderDocumentRepository.Get(cond => cond.OrderDocumentGUID == orderDocumentGUID, null, "TCompany,TOrder").FirstOrDefault();
            string foldername = StaticHelper.GetCOFolder(doc.TCompany.CompanyReferenceNumber, StaticHelper.COFolderConstant);
            string filelocation = Path.Combine(StaticHelper.StorageRoot, foldername, doc.TCompany.CompanyReferenceNumber.ToString(), doc.TOrder.OrderReferenceNumber.ToString(), doc.FileName);

            HttpResponseMessage result = null;
            if (!File.Exists(filelocation))
            {
                result = Request.CreateResponse(HttpStatusCode.NotFound);
            }
            else
            {
                var dataBytes = File.ReadAllBytes(filelocation);
                var dataStream = new MemoryStream(dataBytes);

                result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(dataStream);
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = doc.FileName;
                //result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

                return result;

            }
            return Request.CreateResponse(HttpStatusCode.NotFound);            
        }

Angular serivice

downloadFile(companyGuid: string,orderDocumentGUID: string):Observable<any> {
        let url = this.url + '/' + companyGuid + '/Documents/' + orderDocumentGUID;
        let opt = {
            headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/pdf' }),
            options: new RequestOptions({responseType: ResponseContentType.Blob })
        }
        return this.http.get(url, opt);
    }

Call to service from the component:

this.subscriptions.push(this.companyService.downloadFile(this.currentCompany.Guid, orderDocumentGUID)
            .subscribe(result => {
                console.log('downloadresult', result);
            }))  

Error:

enter image description here

Upvotes: 3

Views: 2998

Answers (1)

sudhir
sudhir

Reputation: 1437

This might be issue with new HttpClient because default the response will be parsed to Json, you can try this

 return this.http.get(url, {responseType: "blob"});

If still the problem exists you can however user Http from '@angular/http'(which will be deprecated) or receive response as text(responseType) and parse it.

Upvotes: 4

Related Questions