javascript - 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>));
}
解决方案
您在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 => { }
);
推荐阅读
- .net - 使用超链接将 RDLC 渲染为 PDF
- matlab - 将归一化滤波器转换为实频滤波器
- excel - 将文件嵌入特定列并向下一行插入另一个文件
- asp.net - 如何更改 Url.Action() 使用的根 URL?
- java - 我们是否需要在 Spring Boot 中为每个表编写实体类?
- amazon-web-services - 在 aws 上创建 https 重定向的步骤
- java - 如何在方法之间调用字符串?
- django - Django Graphene - 将 info.context 传递给 Query 或 Mutation 的装饰器
- python - pandas 序列的唯一 ID
- json - 抓取 AJAX 生成的表格以批量下载 PDF