You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular视图中使用<img>标签显示Blob图片文件?

Blob图片在Angular视图中显示的实现方案

后端基于ASP.NET Core 5提供downloadFile接口返回Blob格式图片,前端使用Angular 15.0调用接口后已获取到Blob对象及对应的blob: URL,需将图片通过<img>标签渲染到视图中,具体实现如下:


相关代码参考

后端接口代码(ASP.NET Core 5)

[HttpGet("downloadFile"), DisableRequestSizeLimit]
public async Task<IActionResult> DownloadFile([FromQuery] string fileUrl)
{
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileUrl);

    if (!System.IO.File.Exists(filePath))
        return NotFound();

    var memory = new MemoryStream();
    await using (var stream = new FileStream(filePath, FileMode.Open))
    {
        await stream.CopyToAsync(memory);
    }
    memory.Position = 0;

    return File(memory, GetContentType(filePath), filePath);
}

private string GetContentType(string path)
{
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    
    if (!provider.TryGetContentType(path, out contentType))
    {
        contentType = "application/octet-stream";
    }
    
    return contentType;
}

前端服务代码(Angular 15)

public download(fileUrl: string) {
    return this.http.get(`${this.baseUrl}/downloadFile?fileUrl=${fileUrl}`, {
        reportProgress: true,
        observe: 'events',
        responseType: 'blob'
    });
}

前端组件接收逻辑(原代码)

this.filesService.download(this.imgUrl).subscribe((event) => {
    if (event.type === HttpEventType.UploadProgress)
    { 
        this.progress = Math.round((100 * event.loaded) / event.total);
    }
    else if (event.type === HttpEventType.Response) {
        this.message = 'Download success.';          
        this.downloadFile(event);
    }
});

private downloadFile = (data: HttpResponse<Blob>) => {
    const BlobFile= new Blob([data.body], { type: data.body.type });
    const url = URL.createObjectURL(BlobFile);
    
    // 需要补充代码将图片显示到视图
}

实现步骤

1. 组件类中定义绑定属性

在组件的TypeScript类中声明一个用于存储图片Blob URL的属性:

// 组件类内添加
imageUrl: string | null = null;

2. 修改downloadFile方法赋值

在downloadFile方法中,将生成的blob: URL赋值给上述属性:

private downloadFile = (data: HttpResponse<Blob>) => {
    const blobFile = new Blob([data.body], { type: data.body.type });
    this.imageUrl = URL.createObjectURL(blobFile);
}

3. 模板中绑定src属性

在组件HTML模板中,将<img>的src绑定到imageUrl,并通过*ngIf避免无效状态:

<img [src]="imageUrl" alt="下载的图片" *ngIf="imageUrl">

4. 组件销毁时释放资源

Blob URL会占用浏览器内存,需在组件销毁时主动释放,避免内存泄漏:

import { OnDestroy } from '@angular/core';

// 组件类实现OnDestroy接口
export class YourComponent implements OnDestroy {
    // ...其他已有代码

    ngOnDestroy(): void {
        if (this.imageUrl) {
            URL.revokeObjectURL(this.imageUrl);
            this.imageUrl = null;
        }
    }
}

内容的提问来源于stack exchange,提问作者R. Nourmandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:10:29