如何使用 Azure Functions 删除 blob?

How to delete a blob using Azure Functions?

我正在创建一个 Azure 函数,当图像上传或添加到特定的 Azure 存储时触发,它执行以下操作: 1.) 调整图像大小 2.) 将图像放到正确的目录中(使用输出绑定) 3.) 删除处理后添加到 Azure 存储的原始 blob 图像。

我已完成该过程中的第 1 步和第 2 步,但我发现几乎没有关于删除 blob 或 API 的文档,这些文档会公开 Azure 存储的方法。 (使用 C#)

示例代码如下:

#r "System.Drawing"
using System;
using ImageResizer;
using System.Drawing;
using System.Drawing.Imaging;

public static void Run(Stream inputImage, string imageName, Stream resizedImage, TraceWriter log)
{
    // Log the file name and size
    log.Info($"C# Blob trigger function Processed blob\n Name:{imageName} \n Size: {inputImage.Length} Bytes");

    // Manipulate the image
    var settings = new ImageResizer.ResizeSettings
    {
        MaxWidth = 400,
        Format = "png"
    };

    ImageResizer.ImageBuilder.Current.Build(inputImage, resizedImage, settings);

    // Delete the Raw Original Image Step
}

当您使用 C# 时,您可以在您的函数中使用多种输入类型,这里是 webjobs sdk cheat sheet 详细介绍了大部分可用类型。

在您的情况下,您可以将输入图像请求为 CloudBlockBlob, which has a delete method. You can call this inside the resizing function or in a separately triggered function to delete the completed blobs. You may need to change your binding direction to inout, see here

目前没有自动清理的绑定。

要删除 blob,您需要

var container = blobClient.GetContainerReference(containerName);
var blockBlob = container.GetBlockBlobReference(fileName);
return blockBlob.DeleteIfExists();

确保在尝试此操作之前关闭所有流,以便不再使用图像。

确保导入正确的引用:

#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Blob;

那你就可以把CloudBlockBlob作为参数类型,删掉:

public static void Run(CloudBlockBlob myBlob, string name, TraceWriter log)
{
    myBlob.DeleteIfExists();
}

如果您使用的是最新的库

Azure.Storage.Blobs

你可以这样删除它...

BlobClient client = new BlobClient("connectionString", "container", "blobName");
client.DeleteIfExists();