【发布时间】:2021-07-22 14:13:31
【问题描述】:
当我从邮递员测试我的 API 时,我可以查看我的图像,但从我的 Angular 应用程序中,我无法查看图像。控制台中没有错误。下面是我尝试过的代码。
Asp.net 网络 API 2
[HttpGet]
[AllowAnonymous]
[Route("api/another")]
public HttpResponseMessage GetFile(int productId)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
IEnumerable<ProductImage> files = _context.ProductImages.Where(p => p.ProductId == productId);
foreach (var item in files)
{
response.Content = new ByteArrayContent(item.Image);
response.Content.Headers.ContentLength = item.Image.LongLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = item.Name;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
}
return response;
}
HTML
<div *ngFor="let img of imageData">
<img [alt]="img.Name" [src]="img.Image">
</div>
component.ts
imageData: any[] = [];
getImages() {
this.image.getProduct().subscribe(res => {
this.imageData = [res];
console.log(res);
});
}
service.ts
getProduct() {
return this.http
.get(this.apiUrl + 'another?' + 'productId=' + 2, {responseType: 'blob'})
.pipe(
retry(2),
catchError(this.handleError),
);
}
【问题讨论】:
-
显而易见的问题:您确定要形成图像的完整路径吗?我没有看到传递给
src属性的 API 路径的完整路径。 -
在您的 API 中,您只返回一个图像。是的,您创建了一个循环,但在每个循环中您都会覆盖内容:
response.Content = new ByteArrayContent(item.Image);,因此您只能获得最后一张图像。您需要在 API 中创建一个返回“文件”的函数并使用 forkJoin 获取图像(或直接用作 src) -
@Eliseo 你能帮我解决这个问题吗?
标签: angular asp.net-web-api angular11 ng-file-upload