[英]Receive formatted 'multipart/form-data' response in Angular 7.x
I am developing an Angular application that shows some images to the user.我正在开发一个向用户显示一些图像的 Angular 应用程序。
I would like to obtain those images from a single REST call to a web service: given the fact i am already uploading the images via a FormData
object, i would like to receive those images in the same way (so, basically, via content-type: multipart/form-data
).我想从对 Web 服务的单个 REST 调用中获取这些图像:鉴于我已经通过
FormData
对象上传图像,我想以相同的方式接收这些图像(因此,基本上,通过content-type: multipart/form-data
)。
At the moment, using the following code:目前,使用以下代码:
this.http.post('api/load', {}, {headers: {'Accept': 'multipart/form-data'},
responseType:'text', observe: 'response'});
i am actually receiving the full body of the response in a text format, like this:我实际上以文本格式接收响应的全文,如下所示:
--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...
But it's in a raw, text format.但它是原始的文本格式。
How can i receive a multipart/form-data
response formatted by its boundaries, or a in clean way in Angular 7.x?我如何接收按边界格式化的
multipart/form-data
响应,或者在 Angular 7.x 中以干净的方式接收?
One of the solution is to implement an interceptor service where you can format multipart/form-data response.解决方案之一是实现拦截器服务,您可以在其中设置多部分/表单数据响应的格式。 For example, your inteceptor will be - multipart.interceptor.ts :
例如,您的拦截器将是 - 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);
}
})
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.