我正在开发一个向用户显示一些图像的Angular应用程序。
我想从对Web服务的单个REST调用中获得这些图像:鉴于我已经通过awk -v RS="" -v FS="[|\n]" '{match($0,/display_name/);
nodename=substr($0,RSTART+17, RLENGTH+10); gsub(/ /, "",nodename);;printf
"(%s)\n",nodename}' ava-ipmi.txt
(overcloud-Controller-2)
(overcloud-Controller-0)
(overcloud-Controller-1)
对象上传图像的事实,我希望以相同的方式接收这些图像(因此,基本上是通过FormData
)。
此刻,使用以下代码:
content-type: multipart/form-data
我实际上正在以文本格式接收整个响应,如下所示:
this.http.post('api/load', {}, {headers: {'Accept': 'multipart/form-data'},
responseType:'text', observe: 'response'});
但是它是原始的文本格式。
我怎么能收到--974b5730-ab25-4554-8a69-444664cab379
Content-Disposition: form-data; name=result
{"bar":[1,2,3,4], "foo": true}
--974b5730-ab25-4554-8a69-444664cab379
Content-Disposition: form-data; name=image; filename=image1.jpg; filename*=utf-8''image1.jpg
--- binarycontent...
的响应,该响应的格式由其边界或在Angular 7.x中以一种简洁的方式构成?
答案 0 :(得分:0)
解决方案之一是实现拦截器服务,您可以在其中格式化多部分/表单数据响应。 例如,您的拦截器将是 - multipart.interceptor.ts :
@Injectable()
export class MultipartInterceptService implements HttpInterceptor {
private parseResponse(response: HttpResponse<any>): HttpResponse<any> {
const headerValue = response.headers.get('Content-Type');
const body = response.body;
const contentTypeArray = headerValue ? headerValue.split(';') : [];
const contentType = contentTypeArray[0];
switch (contentType) {
case 'multipart/form-data':
if (!body) {
return response.clone({ body: {} });
}
const boundary = body?.split('--')[1].split('\r')[0];
const parsed = this.parseData(body, boundary); // function which parse your data depends on its content (image, svg, pdf, json)
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(customRequest).pipe(
map((response: HttpResponse<any>) => {
if (response instanceof HttpResponse) {
return this.parseResponse(response);
}
})
);
}
}