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

如何在C# ASP.NET Core Web API中将Base64字符串数组转换为Zip文件

将Base64字符串列表转换为Zip文件并提供给Angular下载

后端实现(以.NET为例)

假设你基于ASP.NET Core开发后端,以下是正确处理Base64列表并生成Zip文件的代码:

首先要处理每个Base64字符串——如果字符串带data:image/jpeg;base64,这类前缀,必须先移除,再解码为字节数组。接着通过ZipArchive将这些字节数组作为独立文件条目加入压缩包,最后把压缩包流返回给前端。

using System.IO.Compression;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/files")]
public class FilesController : ControllerBase
{
    [HttpPost("download-zip")]
    public IActionResult DownloadZip([FromBody] List<string> base64List)
    {
        using var memoryStream = new MemoryStream();
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            for (int i = 0; i < base64List.Count; i++)
            {
                string base64String = base64List[i];
                // 移除Base64前缀(如果存在)
                if (base64String.StartsWith("data:"))
                {
                    base64String = base64String.Split(',')[1];
                }
                
                byte[] fileBytes = Convert.FromBase64String(base64String);
                // 创建Zip条目,文件名可根据实际业务自定义
                var entry = archive.CreateEntry($"file_{i+1}.bin", CompressionLevel.Optimal);
                
                using var entryStream = entry.Open();
                entryStream.Write(fileBytes, 0, fileBytes.Length);
            }
        }
        
        memoryStream.Position = 0;
        // 返回Zip文件,指定MIME类型和下载文件名
        return File(memoryStream, "application/zip", "downloaded_files.zip");
    }
}

常见问题排查

  • 若Base64字符串带前缀未移除,Convert.FromBase64String会直接抛出解码异常
  • 初始化ZipArchive时要传入true参数,避免Archive自动关闭底层的MemoryStream
  • 写完所有Zip条目后,必须将MemoryStream的位置重置为0,否则前端会收到空流

前端Angular实现

在Angular中,通过HttpClient请求后端接口,接收Blob类型响应后,创建临时下载链接触发浏览器下载:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class FileDownloadService {
  constructor(private http: HttpClient) {}

  downloadZip(base64List: string[]) {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    this.http.post('api/files/download-zip', base64List, {
      headers,
      responseType: 'blob'
    }).subscribe(blob => {
      // 创建临时下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'downloaded_files.zip';
      document.body.appendChild(a);
      a.click();
      // 清理资源,避免内存泄漏
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    });
  }
}

前端注意事项

  • 必须显式设置responseType: 'blob',否则HttpClient会默认将响应解析为JSON,导致下载的Zip文件损坏
  • 下载完成后要调用revokeObjectURL释放临时URL占用的内存

内容的提问来源于stack exchange,提问作者Rahul Mahajan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:15:09