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

如何在Logic App中使用Blob创建Zip文件?求实现示例

使用Blob创建Zip文件的函数实现示例

下面提供两种主流语言的实现方案,可部署为Azure Functions(也可根据需求调整为自定义服务),实现从Blob存储读取文件并打包为Zip后回传至Blob:

Node.js 实现(Azure Functions)

步骤1:安装依赖

在函数项目目录执行:

npm install @azure/storage-blob adm-zip @azure/identity

步骤2:函数代码

const { BlobServiceClient } = require('@azure/storage-blob');
const AdmZip = require('adm-zip');
const { DefaultAzureCredential } = require('@azure/identity');

module.exports = async function (context, req) {
    // 配置参数,可通过环境变量或请求参数传入
    const storageAccountName = process.env.STORAGE_ACCOUNT_NAME;
    const containerName = 'your-container-name';
    const blobNames = req.query.blobNames?.split(',') || ['file1.txt', 'file2.jpg'];
    const zipBlobName = req.query.zipName || 'output.zip';

    // 初始化Blob客户端
    const blobServiceClient = new BlobServiceClient(
        `https://${storageAccountName}.blob.core.windows.net`,
        new DefaultAzureCredential()
    );
    const containerClient = blobServiceClient.getContainerClient(containerName);

    // 创建Zip实例并添加Blob文件
    const zip = new AdmZip();
    for (const blobName of blobNames) {
        const blobClient = containerClient.getBlobClient(blobName);
        const downloadRes = await blobClient.download();
        const blobBuffer = await streamToBuffer(downloadRes.readableStreamBody);
        zip.addFile(blobName, blobBuffer);
    }

    // 上传Zip到Blob存储
    const zipBuffer = zip.toBuffer();
    const zipBlobClient = containerClient.getBlobClient(zipBlobName);
    await zipBlobClient.uploadData(zipBuffer);

    context.res = {
        body: `Zip文件 ${zipBlobName} 已创建并上传至容器 ${containerName}`
    };
};

// 辅助函数:将可读流转为Buffer
async function streamToBuffer(stream) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        stream.on('data', chunk => chunks.push(Buffer.from(chunk)));
        stream.on('end', () => resolve(Buffer.concat(chunks)));
        stream.on('error', reject);
    });
}

使用说明

  • 配置环境变量STORAGE_ACCOUNT_NAME为你的Blob存储账户名
  • 部署为Azure Functions的HTTP触发类型,调用时可通过blobNames和zipName参数指定要打包的文件及输出文件名
  • 可通过Power Automate的Azure Functions连接器调用该函数,直接在工作流中实现Blob转Zip

C# 实现(Azure Functions)

步骤1:安装NuGet包

在项目中安装以下包:

Azure.Storage.Blobs
Microsoft.Azure.Functions.Worker
Microsoft.Azure.Functions.Worker.Extensions.Http

步骤2:函数代码

using Azure.Storage.Blobs;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using System.IO;
using System.IO.Compression;

namespace BlobZipCreator
{
    public class ZipGeneratorFunction
    {
        [Function("BlobToZip")]
        public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
        {
            // 从请求体或环境变量读取配置
            var config = await req.ReadFromJsonAsync<ZipConfig>();
            var storageAccountName = Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_NAME");
            var containerClient = new BlobServiceClient(
                $"https://{storageAccountName}.blob.core.windows.net",
                new Azure.Identity.DefaultAzureCredential()
            ).GetBlobContainerClient(config.ContainerName);

            // 生成Zip流
            using var zipStream = new MemoryStream();
            using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                foreach (var blobName in config.BlobNames)
                {
                    var blobClient = containerClient.GetBlobClient(blobName);
                    using var blobStream = await blobClient.OpenReadAsync();
                    var zipEntry = archive.CreateEntry(blobName);
                    using var entryStream = zipEntry.Open();
                    await blobStream.CopyToAsync(entryStream);
                }
            }
            zipStream.Position = 0;

            // 上传Zip到Blob
            var zipBlobClient = containerClient.GetBlobClient(config.ZipFileName);
            await zipBlobClient.UploadAsync(zipStream, new Azure.Storage.Blobs.Models.BlobHttpHeaders { ContentType = "application/zip" });

            var response = req.CreateResponse(System.Net.HttpStatusCode.OK);
            await response.WriteStringAsync($"Zip文件 {config.ZipFileName} 已生成");
            return response;
        }

        // 配置模型
        public class ZipConfig
        {
            public string ContainerName { get; set; }
            public List<string> BlobNames { get; set; }
            public string ZipFileName { get; set; }
        }
    }
}

使用说明

  • 配置存储账户名环境变量STORAGE_ACCOUNT_NAME
  • 部署后可通过POST请求传入ContainerName、BlobNames、ZipFileName参数触发打包
  • 确保函数服务主体拥有Blob存储的Storage Blob Data Contributor权限,避免读写权限问题

注意事项

  1. 处理大文件时,建议使用流式操作避免内存溢出,不要一次性加载整个文件到内存
  2. 若需在前端实现Blob转Zip,可使用jszip库直接在浏览器中处理,但需注意浏览器内存限制
  3. 无现成连接器时,自定义函数是最灵活的解决方案,可根据业务场景调整触发方式(如Blob触发、定时触发等)

内容的提问来源于stack exchange,提问作者Krishna Kant Bhardwaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:20:13