HTTP 响应应该有图像,但在 Angular 客户端中结果为“已加载:43094 总计:43094 类型:3”

HTTP reponse should have image but instead result with `loaded: 43094 total: 43094 type: 3` in Angular client

我在 angular 中有一个表单,其中一个表单输入是图像。 表单被发送到服务器,如果响应成功,响应应该以图像为主体,以便在浏览器的 devtools network > preview 部分可用。

成功后,客户端应渲染从服务器返回的图像。

这是预期的响应预览:

这是实际响应:

这是向服务器请求和响应处理的代码:

this.certificateService.AddCertificate(this.info).subscribe(
    (upload: HttpEvent<any>) => {
        switch (upload.type) {
            case HttpEventType.DownloadProgress:
                this.isNewPic = false;
                this.certificateService.SetImage(upload);
                break;
        }
    },
    error => { }
);

问题是,作为响应,我得到以下而不是图像:

loaded: 43094 total: 43094 type: 3

导致此问题的原因是什么?如何解决?

**编辑:**

AddCertificate(item: AddCertificateModel): Observable<any> {
    const Url = `${this.appConfig.apiEndpoint}/Certificate/Template/Preview`;
    const formData: FormData = new FormData();
    for (const key in item) {
        if (item.hasOwnProperty(key)) {

            if (item[key] instanceof File) {
                formData.append(key, item[key], item[key].name);
            }
            else if (key == 'KeywordSampleData') {
                formData.append(key, JSON.stringify(item.KeywordSampleData));
            }
            else {
                formData.append(key, item[key]);
            }
        }
    }
    return this.httpClient
        .post(Url, formData, {
            reportProgress: true,
            observe: 'events'
        })
        .pipe(map(response => response || {} as HttpEvent<any>));
}

您在请求中使用了 reportProgress 选项,这意味着只要请求仍在处理中(响应尚未完成),您就会收到报告请求状态。

您的代码中发生的事情是,在 switch 语句中您只处理 HttpEventType.DownloadProgress,但此状态并不代表服务器的最终响应。您需要的 upload.typeHttpEventType.Response。 要获取图像,请将相关案例添加到您的代码中

this.certificateService.AddCertificate(this.info).subscribe(
    (upload: HttpEvent<any>) => {
        switch (upload.type) {
            case HttpEventType.DownloadProgress:
                console.log('the process is done');
                break;
            case HttpEventType.Response:
                console.log('I got the image!');
                this.isNewPic = false;
                this.certificateService.SetImage(upload);
                break;
        }
    },
    error => { }
);