简体   繁体   中英

Receive formatted 'multipart/form-data' response in Angular 7.x

I am developing an Angular application that shows some images to the user.

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 ).

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?

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 :

@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);
                }
            })
        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM