我正在尝试从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);
}
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);
}
从组件调用服务:
this.subscriptions.push(this.companyService.downloadFile(this.currentCompany.Guid, orderDocumentGUID)
.subscribe(result => {
console.log('downloadresult', result);
}))
错误:
答案 0 :(得分:4)
这可能是新HttpClient的问题,因为默认情况下响应将被解析为Json,你可以试试这个
return this.http.get(url, {responseType: "blob"});
如果问题仍然存在,您可以使用来自'@ angular / http'的Http(将被弃用)或接收响应作为文本(responseType)并解析它。