【发布时间】:2018-07-09 21:29:03
【问题描述】:
我正在尝试通过调用 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/pdf 和application/octet-stream。我查看了以下两个 stackoverflow 问题,但无济于事(Question 1、Question 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);
}
角度服务
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);
}))
错误:
【问题讨论】:
-
您是在使用来自@angular/common/http(Angular5)的新HttpClient 还是来自@angular/http 的Http??
-
我正在使用@angular/common/http
标签: asp.net asp.net-mvc angular asp.net-web-api angular5