问题描述
我正在尝试下载文件(pdf,word,excel),该文件在DB中另存为bytes [],下面是我的代码。但是在调用方法时出现错误(意外的令牌错误)。 请指导我修复它。
控制器代码:
[HttpPost]
public async Task<FileResult> AttachmentById([FromBody]ReviewAttachmentModel attachmentRequest)
{
ReviewAttachmentModel model = new ReviewAttachmentModel();
try
{
ReviewAttachmentDto reviewAttachmentDto = new ReviewAttachmentDto
{
DocumentKey = attachmentRequest.DocumentKey,ReviewKey = attachmentRequest.ReviewKey,UserId = attachmentRequest.UserId,};
ReviewAttachmentDto _attachmentDto = reviewAttachmentDto;
string requestBody = JsonConvert.SerializeObject(_attachmentDto);
//Call API
string _responSEObj = await WebAPIHelper.PostDataToAPI(appSettings.ReviewAttachmentUrl,requestBody,this.loggedinUser.CookieCollection,accesstoken);
model = JsonConvert.DeserializeObject<ReviewAttachmentModel>(_responSEObj);
// model.Document - byte[]
return File(model.Document,model.DocumentType,model.DocumentName);
}
catch (Exception ex)
{
return null;
}
}
Service.ts:
public downloadReviewAttachment(reviewAttachmentModel: any): Observable<any> {
this._urlSurveillanceDetails = this.baseHref + "/ReviewProfile/AttachmentById";
const headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type','application/octet-stream');
return this.http.post<any>(this._urlSurveillanceDetails,reviewAttachmentModel,{ headers: headers });
}
Component.ts:
onAttachmentDownload(documentKey: any,reviewKey: any) {
let reviewAttachmentModel: any = {
documentKey: documentKey,reviewKey: reviewKey
};
this._surveillanceService.downloadReviewAttachment(reviewAttachmentModel).subscribe(data => {
if (data != undefined) {
}
})
}
错误:
解决方法
更改此:
public downloadReviewAttachment(reviewAttachmentModel: any): Observable<any> {
this._urlSurveillanceDetails = this.baseHref + "/ReviewProfile/AttachmentById";
const headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type','application/octet-stream');
return this.http.post<any>(this._urlSurveillanceDetails,reviewAttachmentModel,{ headers: headers });
}
对此:
public downloadReviewAttachment(reviewAttachmentModel: any): Observable<blob> {
this._urlSurveillanceDetails = this.baseHref + "/ReviewProfile/AttachmentById";
return this.http.post(this._urlSurveillanceDetails,{ responseType: 'blob'});
}
通过删除通用参数并添加所需的responseType。 Angular知道该怎么做。