gpt4 book ai didi

asp.net - Angular5 和 Web Api - 下载 PDF 文件

转载 作者:太空狗 更新时间:2023-10-29 18:19:10 25 4
gpt4 key购买 nike

我正在尝试通过调用 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。我查看了以下两个 stackoverflow 问题,但无济于事( Question 1Question 2 )。

下面是代码:

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

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

错误:

enter image description here

最佳答案

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

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

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

关于asp.net - Angular5 和 Web Api - 下载 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com