微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

下载FileResult不适用于Angular

如何解决下载FileResult不适用于Angular

我正在尝试下载文件(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) {
      }
    })
  }

错误

enter image description here

解决方法

更改此:

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知道该怎么做。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。