【问题标题】:Angular 5 - Api Swagger body responseType blobAngular 5 - Api Swagger body responseType blob
【发布时间】:2020-07-06 21:33:00
【问题描述】:

我有一个应用程序调用一个返回文件并将它们压缩成 zip 文件的 api。

我创建了自己的服务,它运行良好。

return this.http.get(this.rootUrl + '/api/Files/DownloadFile?files=' + fileSelected + '&user=' + user, { responseType: 'blob' as 'json' }); // working ok

这里的 api 响应必须是一个 blob 对象。

但是当我尝试使用 swagger 生成的服务做同样的事情时,它不再起作用了。

let req = new HttpRequest<any>(
    'GET',
    this.rootUrl + `/api/Files/DownloadFile`, 
    __body, 
    {
    headers: __headers,
    params: __params,
    responseType: 'text'
}
); // not working ok

服务返回 null,但是在 chrome 检查器中,在对 api 调用的响应中,它显示奇怪的字符。

this.filesService.DownloadFile({"files": ids, "user": this.user}).subscribe(
    data => {
        console.log(data); // data value is null but in the response I see strange characters
    },
    err => { 
        console.log(err);
    }
);

这是正常的,因为swagger服务的responseType是“text”,我试过手动把contentType改成“blob”(swagger规范)或者“blob as json”(angular 5),但是没有工作正常。

是否可以使用 swagger 生成的服务从 Angular 解决它,还是我必须触摸 API?谢谢

【问题讨论】:

  • 我也有同样的问题 :((, 不能使用 responseType blob 太可惜了。

标签: angular swagger blob


【解决方案1】:

您可以使用 HttpInterceptor 来更正请求的 responseType。例如。对于返回媒体类型“application/octet-stream”的服务函数:

import {Injectable} from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import {Observable} from 'rxjs';

@Injectable()
export class FileDownloadHttpInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    if (req.headers.get('Accept') === 'application/octet-stream') {
      // @ts-ignore: ignore that responseType is read only
      req.responseType = 'blob';
    }
    return next.handle(req);
  }
}

然后在适当的模块中提供拦截器,例如app.module.ts:

providers: [{
      provide: HTTP_INTERCEPTORS, useClass: FileDownloadHttpInterceptor, multi: true
    }]

最后的步骤取决于您的服务究竟返回什么。对我来说,为服务中的 HttpResponse 调用 window.open(response.url); 就足够了,但也许您必须先将响应转换为 blob,然后将 blob 转换为 URL,请参阅 How do I download a file with Angular2 or greater

P.S.:用 HttpInterceptors 处理请求肯定不是最好的编码风格。在服务生成方面的解决方案将是可取的。但是我发现无法在服务的 den OpenApi 描述中指定 responseType,并且生成的服务不够聪明,无法根据服务声明的返回类型更改其默认的 json 响应类型(或者我不够聪明,无法配置生成器)。

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 2020-08-11
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2021-04-12
    • 2021-09-17
    相关资源
    最近更新 更多