以下是一个 Azure Function 的示例代码,可以返回指定路径下的 Blob 对象:

using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public static class GetBlobFunction
{
    [FunctionName('GetBlob')]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, 'get', Route = 'blobs/{container}/{*blobName}')] HttpRequest req,
        string container,
        string blobName,
        ILogger log)
    {
        log.LogInformation($'GetBlob function processed a request for container '{container}' and blob '{blobName}'.');

        // Retrieve the storage account connection string and blob client
        string connectionString = Environment.GetEnvironmentVariable('AzureWebJobsStorage');
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve the container reference and the blob reference
        CloudBlobContainer blobContainer = blobClient.GetContainerReference(container);
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(blobName);

        // Check if the blob exists
        if (!await blob.ExistsAsync())
        {
            return new NotFoundResult();
        }

        // Read the blob content into a memory stream
        using (var memoryStream = new MemoryStream())
        {
            await blob.DownloadToStreamAsync(memoryStream);
            var blobContent = memoryStream.ToArray();

            // Return the blob content as a stream response
            return new FileStreamResult(new MemoryStream(blobContent), blob.Properties.ContentType);
        }
    }
}

该函数使用 HTTP 触发器,可以通过以下 URL 访问它:

https://<function_app_name>.azurewebsites.net/api/blobs/<container_name>/<blob_path>

其中,<function_app_name> 是你的 Azure Function App 的名称,<container_name> 是 Blob 存储中的容器名称,<blob_path> 是要获取的 Blob 对象的路径和文件名。例如,如果要获取 mycontainer 容器中的 images/logo.png 文件,可以使用以下 URL:

https://<function_app_name>.azurewebsites.net/api/blobs/mycontainer/images/logo.png

函数将返回 Blob 对象的内容作为流响应。如果 Blob 对象不存在,则会返回 404 Not Found 响应。

Azure Function: 获取 Blob 对象内容

原文地址: https://www.cveoy.top/t/topic/oLFe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录