首页 > 解决方案 > HTTP 响应应该有图像,但结果是 Angular 客户端中的 `loaded: 43094 total: 43094 type: 3`

问题描述

我有一个角度形式的表格,其中一个表格输入是图像。表单被发送到服务器,如果响应成功,则响应应该将图像作为其主体,以便在浏览器的 devtoolsnetwork > 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>));
}

标签: javascriptangulartypescripthttpclient

解决方案


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

您的代码中发生的情况是,在switch您处理的语句中仅处理HttpEventType.DownloadProgress,但此状态并不代表来自服务器的最终响应。upload.type你需要的是HttpEventType.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 => { }
);

推荐阅读