Angular5 和 Web Api - 下载 PDF 文件

Angular5 and Web Api - Download a PDF file

我正在尝试通过调用 Angular 5.2 应用程序中的 Web Api 服务来下载 pdf 文件。 api 调用返回 200,似乎正确返回 PDF 文档,但我收到以下错误:

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

由于从未到达 .subscribe() 方法,拦截响应的代码似乎引发了此错误。我已经尝试使用 application/pdfapplication/octet-stream。我查看了以下两个计算器问题,但无济于事(Question 1, )。

下面是代码:

网络Api -

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 服务

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);
    }

从组件调用服务:

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

错误:

这可能是新 HttpClient 的问题,因为默认响应将被解析为 Json,您可以试试这个

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

如果问题仍然存在,您可以使用来自“@angular/http”的 Http(将被弃用)或接收文本形式的响应(responseType)并解析它。