How to get the data returned(back-end) after an Upload (form-data) request ends?

Issue

I have an upload method that monitor the progress.
The upload works just fine, but at the end, my back-end sends me an object (register) of this file uploaded (id and etc.)

I don’t know how to capture it. What pipe to use or what return type to change into.

Any help?

The content of my upload method

[...]

        const formData = new FormData();
        formData.append('orderDate', orderDate);
        formData.append('file', fileToUpload.data, fileToUpload.name);

        const options: any = {
            observe: 'events',
            reportProgress: true,
        };

        fileToUpload.isUploading = true;
        
        return this.http.post<HttpEvent<Object>>(url, formData, options)
            .pipe(
                map((ev: HttpEvent<Object>) => {

                    if (ev.type === HttpEventType.Response) {

                        fileToUpload.isUploading = false;

                    } else if (ev.type === HttpEventType.UploadProgress) {

                        const percentDone = Math.round((ev.loaded * 100) / ev.total);
                        fileToUpload.uploadProgress = percentDone;
                        fileToUpload.isUploading = true;
                    }
                })
            );

Solution

You have to create Register interface and cast it in if condition. If possible share an example in StackBlitz

 return this.http.post<HttpEvent<Object>>(url, formData, options)
            .pipe(
                map((ev: HttpEvent<Object>) => {

                    if (ev.type === HttpEventType.Response) {

                        fileToUpload.isUploading = false;
                        console.log(ev);

                    } else if (ev.type === HttpEventType.UploadProgress) {

                        const percentDone = Math.round((ev.loaded * 100) / ev.total);
                        fileToUpload.uploadProgress = percentDone;
                        fileToUpload.isUploading = true;
                    }
                })
            );

Answered By – Pavan Jadda

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.