我做了一个快速而肮脏的解决方案,深受启发这另一篇文章 https://stackoverflow.com/a/40657435/1697459在 stackoverflow 上并创建了一个 http 拦截器类,该类展示了如何解析多部分响应。
拦截器返回第一个“application/json”部分作为多部分响应的响应正文(multipart/mixed
, multipart/form-data
or multipart/related
)。
通过映射,可以轻松地将其他内容类型的附加解析器添加到类中。
我将在这里分享这段代码,它可能会给其他人带来启发:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class MultipartInterceptService implements HttpInterceptor {
private parserMap = {
'application/json': JSON.parse,
};
private parseMultipart(multipart: string, boundary: string): any {
const dataArray: string[] = multipart.split(`--${boundary}`);
dataArray.shift();
dataArray.forEach((dataBlock) => {
const rows = dataBlock.split(/\r?\n/).splice(1, 4);
if (rows.length < 1) {
return;
}
const headers = rows.splice(0, 2);
const body = rows.join('');
if (headers.length > 1) {
const pattern = /Content-Type: ([a-z\/+]+)/g;
const match = pattern.exec(headers[0]);
if (match === null) {
throw Error('Unable to find Content-Type header value');
}
const contentType = match[1];
if (this.parserMap.hasOwnProperty(contentType) === true) {
return this.parserMap[contentType](body);
}
}
});
return false;
}
private parseResponse(response: HttpResponse<any>): HttpResponse<any> {
const contentTypeHeaderValue = response.headers.get('Content-Type');
const body = response.body;
const contentTypeArray = contentTypeHeaderValue.split(';');
const contentType = contentTypeArray[0];
switch (contentType) {
case 'multipart/related':
case 'multipart/mixed':
case 'multipart/form-data':
const boundary = contentTypeArray[1].split('boundary=')[1];
const parsed = this.parseMultipart(body, boundary);
if (parsed === false) {
throw Error('Unable to parse multipart response');
}
return response.clone({ body: parsed });
default:
return response;
}
}
// intercept request and add parse custom response
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
map((response: HttpResponse<any>) => {
if (response instanceof HttpResponse) {
return this.parseResponse(response);
}
}),
);
}
}
该代码读取边界Content-Type
响应标头并使用此边界将响应正文拆分为块。然后它尝试解析每个部分并返回第一个成功解析的部分application/json
阻止响应。
如果您有兴趣返回另一个代码块或者您想在最终响应中组合多个代码块,您将需要自己的解析器或更改逻辑。这需要对代码进行一些定制。
NOTE:该代码是实验性的,并且经过有限的测试,尚未准备好投入生产,使用时要小心。