您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

Azure Functions 的 Azure Blob 存储绑定Azure Blob storage bindings for Azure Functions

本文介绍如何在 Azure Functions 中使用 Azure Blob 存储绑定。This article explains how to work with Azure Blob storage bindings in Azure Functions. Azure Functions 支持 Blob 的触发器、输入和输出绑定。Azure Functions supports trigger, input, and output bindings for blobs. 本文各部分分别介绍每种绑定:The article includes a section for each binding:

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

备注

将事件网格触发器而非 Blob 存储触发器用于仅限 Blob 的存储帐户、大规模,或者降低延迟。Use the Event Grid trigger instead of the Blob storage trigger for blob-only storage accounts, for high scale, or to reduce latency. 有关详细信息,请参阅触发器部分。For more information, see the Trigger section.

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs NuGet 包 2.x 版中提供了 Blob 存储绑定。The Blob storage bindings are provided in the Microsoft.Azure.WebJobs NuGet package, version 2.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

在所有开发环境中自动提供对该绑定的支持。Support for this binding is automatically provided in all development environments. 无需手动安装包或注册扩展。You don't have to manually install the package or register the extension.

Functions 1.x 中的 Azure 存储 SDK 版本Azure Storage SDK version in Functions 1.x

在 Functions 1.x 中,存储触发器和绑定使用 Azure 存储 SDK 版本 7.2.1(WindowsAzure.Storage NuGet 包)。In Functions 1.x, the Storage triggers and bindings use version 7.2.1 of the Azure Storage SDK (WindowsAzure.Storage NuGet package). 如果引用不同版本的存储 SDK 并绑定到函数签名中的一种存储 SDK 类型,Functions 运行时可能报告无法绑定到该类型。If you reference a different version of the Storage SDK, and you bind to a Storage SDK type in your function signature, the Functions runtime may report that it can't bind to that type. 解决办法是确保项目引用 WindowsAzure.Storage 7.2.1The solution is to make sure your project references WindowsAzure.Storage 7.2.1.

包 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.Storage NuGet 包 3.x 版中提供了 Blob 存储绑定。The Blob storage bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Storage NuGet package, version 3.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

触发器Trigger

检测到新的或更新的 Blob 时,Blob 存储触发器会启动某个函数。The Blob storage trigger starts a function when a new or updated blob is detected. Blob 内容会作为输入提供给函数。The blob contents are provided as input to the function.

事件网格触发器提供对 Blob 事件的内置支持,也可用来在检测到新的或更新的 Blob 时启动函数。The Event Grid trigger has built-in support for blob events and can also be used to start a function when a new or updated blob is detected. 如需示例,请参阅使用事件网格调整图像大小教程。For an example, see the Image resize with Event Grid tutorial.

以下方案请使用事件网格而不是 Blob 存储触发器:Use Event Grid instead of the Blob storage trigger for the following scenarios:

  • Blob 存储帐户Blob storage accounts
  • 大规模High scale
  • 最大程度地降低延迟Minimizing latency

Blob 存储帐户Blob storage accounts

Blob 存储帐户适用于 Blob 输入和输出绑定,但不适用于 Blob 触发器。Blob storage accounts are supported for blob input and output bindings but not for blob triggers. Blob 存储触发器需要使用常规用途存储帐户。Blob storage triggers require a general-purpose storage account.

大规模High scale

大规模可以宽松地定义为包含 100,000 个以上的 Blob 的容器,或者定义为每秒进行 100 个以上 Blob 更新的存储帐户。High scale can be loosely defined as containers that have more than 100,000 blobs in them or storage accounts that have more than 100 blob updates per second.

延迟问题Latency issues

如果函数应用基于消耗计划,则当函数应用处于空闲状态时,处理新 Blob 会出现长达 10 分钟的延迟。If your function app is on the Consumption plan, there can be up to a 10-minute delay in processing new blobs if a function app has gone idle. 若要避免此延迟,可以切换到启用了 Always On 的应用服务计划。To avoid this latency, you can switch to an App Service plan with Always On enabled. 还可以为 Blob 存储帐户使用事件网格触发器You can also use an Event Grid trigger with your Blob storage account. 有关示例,请参阅事件网格教程For an example, see the Event Grid tutorial.

队列存储触发器Queue storage trigger

除了事件网格,还可以使用其他方法来处理 Blob,例如使用队列存储触发器,但后者没有针对 Blob 事件的内置支持。Besides Event Grid, another alternative for processing blobs is the Queue storage trigger, but it has no built-in support for blob events. 在创建或更新 Blob 时,必须创建队列消息。You would have to create queue messages when creating or updating blobs. 如需假定你已完成该操作的示例,请参阅本文后面部分的 Blob 输入绑定示例For an example that assumes you've done that, see the blob input binding example later in this article.

触发器 - 示例Trigger - example

参阅语言特定的示例:See the language-specific example:

触发器 - C# 示例Trigger - C# example

以下示例演示在 samples-workitems 容器中添加或更新 blob 时写入日志的 C# 函数The following example shows a C# function that writes a log when a blob is added or updated in the samples-workitems container.

[FunctionName("BlobTriggerCSharp")]        
public static void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}

blob 触发器路径 samples-workitems/{name} 中的字符串 {name} 会创建一个绑定表达式,可以在函数代码中使用它来访问触发 blob 的文件名。The string {name} in the blob trigger path samples-workitems/{name} creates a binding expression that you can use in function code to access the file name of the triggering blob. 有关详细信息,请参阅本文下文中的 Blob 名称模式For more information, see Blob name patterns later in this article.

有关 BlobTrigger 特性的详细信息,请参阅触发器 - 特性For more information about the BlobTrigger attribute, see Trigger - attributes.

触发器 - C# 脚本示例Trigger - C# script example

以下示例显示了 function.json 文件中的一个 Blob 触发器绑定以及使用该绑定的 Python 代码The following example shows a blob trigger binding in a function.json file and Python code that uses the binding. samples-workitems 容器中添加或更新 Blob 时,该函数会写入一条日志。The function writes a log when a blob is added or updated in the samples-workitems container.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "name": "myBlob",
            "type": "blobTrigger",
            "direction": "in",
            "path": "samples-workitems/{name}",
            "connection":"MyStorageAccountAppSetting"
        }
    ]
}

blob 触发器路径 samples-workitems/{name} 中的字符串 {name} 会创建一个绑定表达式,可以在函数代码中使用它来访问触发 blob 的文件名。The string {name} in the blob trigger path samples-workitems/{name} creates a binding expression that you can use in function code to access the file name of the triggering blob. 有关详细信息,请参阅本文下文中的 Blob 名称模式For more information, see Blob name patterns later in this article.

有关 function.json 文件属性的详细信息,请参阅解释了这些属性的配置部分。For more information about function.json file properties, see the Configuration section explains these properties.

下面是绑定到 Stream 的 C# 脚本代码:Here's C# script code that binds to a Stream:

public static void Run(Stream myBlob, string name, ILogger log)
{
   log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}

下面是绑定到 CloudBlockBlob 的 C# 脚本代码:Here's C# script code that binds to a CloudBlockBlob:

#r "Microsoft.WindowsAzure.Storage"

using Microsoft.WindowsAzure.Storage.Blob;

public static void Run(CloudBlockBlob myBlob, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name}\nURI:{myBlob.StorageUri}");
}

触发器 - JavaScript 示例Trigger - JavaScript example

以下示例显示了 function.json 文件中的一个 Blob 触发器绑定以及使用该绑定的 JavaScript 代码The following example shows a blob trigger binding in a function.json file and JavaScript code that uses the binding. samples-workitems 容器中添加或更新 Blob 时,该函数会写入日志。The function writes a log when a blob is added or updated in the samples-workitems container.

function.json 文件如下所示:Here's the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "name": "myBlob",
            "type": "blobTrigger",
            "direction": "in",
            "path": "samples-workitems/{name}",
            "connection":"MyStorageAccountAppSetting"
        }
    ]
}

blob 触发器路径 samples-workitems/{name} 中的字符串 {name} 会创建一个绑定表达式,可以在函数代码中使用它来访问触发 blob 的文件名。The string {name} in the blob trigger path samples-workitems/{name} creates a binding expression that you can use in function code to access the file name of the triggering blob. 有关详细信息,请参阅本文下文中的 Blob 名称模式For more information, see Blob name patterns later in this article.

有关 function.json 文件属性的详细信息,请参阅解释了这些属性的配置部分。For more information about function.json file properties, see the Configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function(context) {
    context.log('Node.js Blob trigger function processed', context.bindings.myBlob);
    context.done();
};

触发器 - Python 示例Trigger - Python example

以下示例显示了 function.json 文件中的一个 Blob 触发器绑定以及使用该绑定的 Python 代码The following example shows a blob trigger binding in a function.json file and Python code that uses the binding. samples-workitems 容器中添加或更新 Blob 时,该函数会写入一条日志。The function writes a log when a blob is added or updated in the samples-workitems container.

function.json 文件如下所示:Here's the function.json file:

{
    "scriptFile": "__init__.py",
    "disabled": false,
    "bindings": [
        {
            "name": "myblob",
            "type": "blobTrigger",
            "direction": "in",
            "path": "samples-workitems/{name}",
            "connection":"MyStorageAccountAppSetting"
        }
    ]
}

blob 触发器路径 samples-workitems/{name} 中的字符串 {name} 会创建一个绑定表达式,可以在函数代码中使用它来访问触发 blob 的文件名。The string {name} in the blob trigger path samples-workitems/{name} creates a binding expression that you can use in function code to access the file name of the triggering blob. 有关详细信息,请参阅本文下文中的 Blob 名称模式For more information, see Blob name patterns later in this article.

有关 function.json 文件属性的详细信息,请参阅解释了这些属性的配置部分。For more information about function.json file properties, see the Configuration section explains these properties.

下面是 Python 代码:Here's the Python code:

import logging
import azure.functions as func


def main(myblob: func.InputStream):
    logging.info('Python Blob trigger function processed %s', myblob.name)

触发器 - Java 示例Trigger - Java example

以下示例显示了 function.json 文件中的一个 Blob 触发器绑定以及使用该绑定的 Java 代码The following example shows a blob trigger binding in a function.json file and Java code that uses the binding. myblob 容器中添加或更新 Blob 时,该函数会写入日志。The function writes a log when a blob is added or updated in the myblob container.

function.json 文件如下所示:Here's the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "name": "file",
            "type": "blobTrigger",
            "direction": "in",
            "path": "myblob/{name}",
            "connection":"MyStorageAccountAppSetting"
        }
    ]
}

下面是 Java 代码:Here's the Java code:

@FunctionName("blobprocessor")
public void run(
  @BlobTrigger(name = "file",
               dataType = "binary",
               path = "myblob/{name}",
               connection = "MyStorageAccountAppSetting") byte[] content,
  @BindingName("name") String filename,
  final ExecutionContext context
) {
  context.getLogger().info("Name: " + filename + " Size: " + content.length + " bytes");
}

触发器 - 特性Trigger - attributes

对于 C# 类库,请使用以下属性来配置 blob 触发器:In C# class libraries, use the following attributes to configure a blob trigger:

  • BlobTriggerAttributeBlobTriggerAttribute

    该特性的构造函数采用一个表示要监视的容器的路径字符串,并选择性地采用某种 Blob 名称模式The attribute's constructor takes a path string that indicates the container to watch and optionally a blob name pattern. 以下是一个示例:Here's an example:

    [FunctionName("ResizeImage")]
    public static void Run(
        [BlobTrigger("sample-images/{name}")] Stream image,
        [Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageSmall)
    {
        ....
    }
    

    可以设置 Connection 属性来指定要使用的存储帐户,如以下示例中所示:You can set the Connection property to specify the storage account to use, as shown in the following example:

    [FunctionName("ResizeImage")]
    public static void Run(
        [BlobTrigger("sample-images/{name}", Connection = "StorageConnectionAppSetting")] Stream image,
        [Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageSmall)
    {
        ....
    }
    

    有关完整示例,请参阅触发器 - C# 示例For a complete example, see Trigger - C# example.

  • StorageAccountAttributeStorageAccountAttribute

    提供另一种方式来指定要使用的存储帐户。Provides another way to specify the storage account to use. 构造函数采用包含存储连接字符串的应用设置的名称。The constructor takes the name of an app setting that contains a storage connection string. 可以在参数、方法或类级别应用该特性。The attribute can be applied at the parameter, method, or class level. 以下示例演示类级别和方法级别:The following example shows class level and method level:

    [StorageAccount("ClassLevelStorageAppSetting")]
    public static class AzureFunctions
    {
        [FunctionName("BlobTrigger")]
        [StorageAccount("FunctionLevelStorageAppSetting")]
        public static void Run( //...
    {
        ....
    }
    

要使用的存储帐户按以下顺序确定:The storage account to use is determined in the following order:

  • BlobTrigger 特性的 Connection 属性。The BlobTrigger attribute's Connection property.
  • 作为 BlobTrigger 特性应用到同一参数的 StorageAccount 特性。The StorageAccount attribute applied to the same parameter as the BlobTrigger attribute.
  • 应用到函数的 StorageAccount 特性。The StorageAccount attribute applied to the function.
  • 应用到类的 StorageAccount 特性。The StorageAccount attribute applied to the class.
  • 函数应用的默认存储帐户(“AzureWebJobsStorage”应用设置)。The default storage account for the function app ("AzureWebJobsStorage" app setting).

触发器 - 配置Trigger - configuration

下表解释了在 function.json 文件和 BlobTrigger 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the BlobTrigger attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 blobTriggerMust be set to blobTrigger. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 必须设置为 inMust be set to in. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal. 用法部分中已阐述异常。Exceptions are noted in the usage section.
名称name 不适用n/a 表示函数代码中的 Blob 的变量的名称。The name of the variable that represents the blob in function code.
路径path BlobPathBlobPath 要监视的容器The container to monitor. 可以是某种 Blob 名称模式May be a blob name pattern.
连接connection ConnectionConnection 包含要用于此绑定的存储连接字符串的应用设置的名称。The name of an app setting that contains the Storage connection string to use for this binding. 如果应用设置名称以“AzureWebJobs”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." 如果将 connection 留空,函数运行时将使用名为 AzureWebJobsStorage 的应用设置中的默认存储连接字符串。If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

连接字符串必须属于某个常规用途存储帐户,而不能属于Blob 存储帐户The connection string must be for a general-purpose storage account, not a Blob storage account.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

触发器 - 用法Trigger - usage

在 C# 和 C# 脚本中,可以为触发 blob 使用以下参数类型:In C# and C# script, you can use the following parameter types for the triggering blob:

  • Stream
  • TextReader
  • string
  • Byte[]
  • 可序列化为 JSON 的 POCOA POCO serializable as JSON
  • ICloudBlob1ICloudBlob1
  • CloudBlockBlob1CloudBlockBlob1
  • CloudPageBlob1CloudPageBlob1
  • CloudAppendBlob1CloudAppendBlob1

1 function.json 中需有 "inout" 绑定 direction 或 C# 类库中需有 FileAccess.ReadWrite1 Requires "inout" binding direction in function.json or FileAccess.ReadWrite in a C# class library.

如果尝试绑定到某个存储 SDK 类型并收到错误消息,请确保已引用正确的存储 SDK 版本If you try to bind to one of the Storage SDK types and get an error message, make sure that you have a reference to the correct Storage SDK version.

由于整个 Blob 内容都会加载到内存中,因此,只有当 Blob 较小时才建议绑定到 stringByte[] 或 POCO。Binding to string, Byte[], or POCO is only recommended if the blob size is small, as the entire blob contents are loaded into memory. 平时,最好使用 StreamCloudBlockBlob 类型。Generally, it is preferable to use a Stream or CloudBlockBlob type. 有关详细信息,请参阅本文后面的并发和内存使用情况For more information, see Concurrency and memory usage later in this article.

在 JavaScript 中,可以使用 context.bindings.<name from function.json> 访问输入 Blob 数据。In JavaScript, access the input blob data using context.bindings.<name from function.json>.

触发器 - Blob 名称模式Trigger - blob name patterns

可以在 function.jsonpath 属性中或者在 BlobTrigger 特性构造函数中指定 Blob 名称模式。You can specify a blob name pattern in the path property in function.json or in the BlobTrigger attribute constructor. 名称模式可以是筛选器或绑定表达式The name pattern can be a filter or binding expression. 以下部分提供了有关示例。The following sections provide examples.

获取文件名和扩展名Get file name and extension

以下示例演示如何分别绑定到 Blob 文件名和扩展名:The following example shows how to bind to the blob file name and extension separately:

"path": "input/{blobname}.{blobextension}",

如果 Blob 名为 original-Blob1.txt,则函数代码中 blobnameblobextension 变量的值为 original-Blob1txtIf the blob is named original-Blob1.txt, the values of the blobname and blobextension variables in function code are original-Blob1 and txt.

按 Blob 名称筛选Filter on blob name

以下示例仅根据 input 容器中以字符串“original-”开头的 Blob 触发:The following example triggers only on blobs in the input container that start with the string "original-":

"path": "input/original-{name}",

如果 Blob 名称为 original-Blob1.txt,则函数代码中 name 变量的值为 Blob1If the blob name is original-Blob1.txt, the value of the name variable in function code is Blob1.

按文件类型筛选Filter on file type

以下示例仅根据 .png 文件触发:The following example triggers only on .png files:

"path": "samples/{name}.png",

按文件名中的大括号筛选Filter on curly braces in file names

若要查找文件名中的大括号,请使用两个大括号将大括号转义。To look for curly braces in file names, escape the braces by using two braces. 以下示例筛选名称中包含大括号的 Blob:The following example filters for blobs that have curly braces in the name:

"path": "images/{{20140101}}-{name}",

如果 Blob 名为 {20140101}-soundfile.mp3,则函数代码中的 name 变量值为 soundfile.mp3If the blob is named {20140101}-soundfile.mp3, the name variable value in the function code is soundfile.mp3.

触发器 - 元数据Trigger - metadata

Blob 触发器提供了几个元数据属性。The blob trigger provides several metadata properties. 这些属性可在其他绑定中用作绑定表达式的一部分,或者用作代码中的参数。These properties can be used as part of binding expressions in other bindings or as parameters in your code. 这些值的语义与 CloudBlob 类型相同。These values have the same semantics as the CloudBlob type.

属性Property typeType 描述Description
BlobTrigger string 触发 Blob 的路径。The path to the triggering blob.
Uri System.Uri 主位置的 blob 的 URI。The blob's URI for the primary location.
Properties BlobPropertiesBlobProperties Blob 的系统属性。The blob's system properties.
Metadata IDictionary<string,string> Blob 的用户定义元数据。The user-defined metadata for the blob.

例如,以下 C# 脚本和 JavaScript 示例会记录触发 blob 的路径,包括容器:For example, the following C# script and JavaScript examples log the path to the triggering blob, including the container:

public static void Run(string myBlob, string blobTrigger, ILogger log)
{
    log.LogInformation($"Full blob path: {blobTrigger}");
} 
module.exports = function (context, myBlob) {
    context.log("Full blob path:", context.bindingData.blobTrigger);
    context.done();
};

触发器 - Blob 回执Trigger - blob receipts

Azure Functions 运行时确保没有为相同的新 blob 或更新 blob 多次调用 blob 触发器函数。The Azure Functions runtime ensures that no blob trigger function gets called more than once for the same new or updated blob. 为了确定是否已处理给定的 blob 版本,它会维护 blob 回执。To determine if a given blob version has been processed, it maintains blob receipts.

Azure Functions 将 Blob 回执存储在函数应用的 Azure 存储帐户中名为 azure-webjobs-hosts 的容器中(由 AzureWebJobsStorage 应用设置定义)。Azure Functions stores blob receipts in a container named azure-webjobs-hosts in the Azure storage account for your function app (defined by the app setting AzureWebJobsStorage). Blob 回执包含以下信息:A blob receipt has the following information:

  • 触发的函数("<function app name>.Functions.<function name>",例如:"MyFunctionApp.Functions.CopyBlob")The triggered function ("<function app name>.Functions.<function name>", for example: "MyFunctionApp.Functions.CopyBlob")
  • 容器名称The container name
  • Blob 类型("BlockBlob" 或 "PageBlob")The blob type ("BlockBlob" or "PageBlob")
  • Blob 名称The blob name
  • ETag(blob 版本标识符,例如:"0x8D1DC6E70A277EF")The ETag (a blob version identifier, for example: "0x8D1DC6E70A277EF")

若要强制重新处理某个 blob,可从 azure-webjobs-hosts 容器中手动删除该 blob 的 blob 回执。To force reprocessing of a blob, delete the blob receipt for that blob from the azure-webjobs-hosts container manually. 虽然重新处理可能不会立即发生,但它肯定会在稍后的时间点发生。While reprocessing might not occur immediately, it's guaranteed to occur at a later point in time.

触发器 - 有害 BlobTrigger - poison blobs

当给定 blob 的 blob 触发函数失败时,Azure Functions 将默认重试该函数共计 5 次。When a blob trigger function fails for a given blob, Azure Functions retries that function a total of 5 times by default.

如果 5 次尝试全部失败,Azure Functions 会将消息添加到名为 webjobs-blobtrigger-poison 的存储队列。If all 5 tries fail, Azure Functions adds a message to a Storage queue named webjobs-blobtrigger-poison. 有害 Blob 的队列消息是包含以下属性的 JSON 对象:The queue message for poison blobs is a JSON object that contains the following properties:

  • FunctionId(格式为 <function app name>.Functions.<function name>)FunctionId (in the format <function app name>.Functions.<function name>)
  • BlobType("BlockBlob" 或 "PageBlob")BlobType ("BlockBlob" or "PageBlob")
  • ContainerNameContainerName
  • BlobNameBlobName
  • ETag(blob 版本标识符,例如:"0x8D1DC6E70A277EF")ETag (a blob version identifier, for example: "0x8D1DC6E70A277EF")

触发器 - 并发和内存使用情况Trigger - concurrency and memory usage

Blob 触发器可在内部使用队列,因此并发函数调用的最大数量受 host.json 中的队列配置控制。The blob trigger uses a queue internally, so the maximum number of concurrent function invocations is controlled by the queues configuration in host.json. 默认设置会将并发限制到 24 个调用。The default settings limit concurrency to 24 invocations. 此限制分别应用于使用 blob 触发器的函数。This limit applies separately to each function that uses a blob trigger.

消耗计划将虚拟机 (VM) 上的函数应用限制为 1.5 GB 内存。The consumption plan limits a function app on one virtual machine (VM) to 1.5 GB of memory. 内存由每个并发执行函数实例和函数运行时本身使用。Memory is used by each concurrently executing function instance and by the Functions runtime itself. 如果 blob 触发的函数将整个 blob 加载到内存中,该函数使用的仅用于 blob 的最大内存为 24 * 最大 blob 大小。If a blob-triggered function loads the entire blob into memory, the maximum memory used by that function just for blobs is 24 * maximum blob size. 例如,包含 3 个由 blob 触发的函数的函数应用和默认设置,其每 VM 最大并发为 3*24 = 72 个函数调用。For example, a function app with three blob-triggered functions and the default settings would have a maximum per-VM concurrency of 3*24 = 72 function invocations.

JavaScript 和 Java 函数会将整个 blob 加载到内存中,并且如果绑定到 stringByte[] 或 POCO,则 C# 函数也会如此。JavaScript and Java functions load the entire blob into memory, and C# functions do that if you bind to string, Byte[], or POCO.

触发器 - 轮询Trigger - polling

如果受监视的 blob 容器包含 10,000 多个 blob(跨所有容器),则 Functions 运行时将扫描日志文件,监视新的或更改的 blob。If the blob container being monitored contains more than 10,000 blobs (across all containers), the Functions runtime scans log files to watch for new or changed blobs. 此过程可能会导致延迟。This process can result in delays. 创建 blob 之后数分钟或更长时间内可能仍不会触发函数。A function might not get triggered until several minutes or longer after the blob is created.

警告

此外,将“尽力”创建存储日志In addition, storage logs are created on a "best effort" basis. 不保证捕获所有事件。There's no guarantee that all events are captured. 在某些情况下可能会遗漏某些日志。Under some conditions, logs may be missed.

如果需要更快或更可靠的 blob 处理,在创建 blob 时,请考虑创建队列消息If you require faster or more reliable blob processing, consider creating a queue message when you create the blob. 然后,使用队列触发器而不是 Blob 触发器来处理 Blob。Then use a queue trigger instead of a blob trigger to process the blob. 另一个选项是使用事件网格;请参阅教程使用事件网格自动调整上传图像的大小Another option is to use Event Grid; see the tutorial Automate resizing uploaded images using Event Grid.

输入Input

使用 blob 存储输入绑定读取 blob。Use a Blob storage input binding to read blobs.

输入 - 示例Input - example

参阅语言特定的示例:See the language-specific example:

输入 - C# 示例Input - C# example

以下示例演示使用一个队列触发器和一个 blob 输入绑定的 C# 函数The following example is a C# function that uses a queue trigger and an input blob binding. 队列消息包含该 blob 的名称,函数记录该 blob 的大小。The queue message contains the name of the blob, and the function logs the size of the blob.

[FunctionName("BlobInput")]
public static void Run(
    [QueueTrigger("myqueue-items")] string myQueueItem,
    [Blob("samples-workitems/{queueTrigger}", FileAccess.Read)] Stream myBlob,
    ILogger log)
{
    log.LogInformation($"BlobInput processed blob\n Name:{myQueueItem} \n Size: {myBlob.Length} bytes");
}

输入 - C# 脚本示例Input - C# script example

以下示例演示 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 C# 脚本 (.csx) 代码。The following example shows blob input and output bindings in a function.json file and C# script (.csx) code that uses the bindings. 此函数创建文本 blob 的副本。The function makes a copy of a text blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

public static void Run(string myQueueItem, string myInputBlob, out string myOutputBlob, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    myOutputBlob = myInputBlob;
}

输入 - JavaScript 示例Input - JavaScript example

下面的示例展示了 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 JavaScript 代码The following example shows blob input and output bindings in a function.json file and JavaScript code that uses the bindings. 该函数创建 Blob 的副本。The function makes a copy of a blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function(context) {
    context.log('Node.js Queue trigger function processed', context.bindings.myQueueItem);
    context.bindings.myOutputBlob = context.bindings.myInputBlob;
    context.done();
};

输入 - Python 示例Input - Python example

下面的示例展示了 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 Python 代码The following example shows blob input and output bindings in a function.json file and Python code that uses the bindings. 该函数创建 Blob 的副本。The function makes a copy of a blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "queuemsg",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "inputblob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false,
  "scriptFile": "__init__.py"
}

配置部分解释了这些属性。The configuration section explains these properties.

下面是 Python 代码:Here's the Python code:

import logging
import azure.functions as func


def main(queuemsg: func.QueueMessage, inputblob: func.InputStream) -> func.InputStream:
    logging.info('Python Queue trigger function processed %s', inputblob.name)
    return inputblob

输入 - Java 示例Input - Java examples

本部分包含以下示例:This section contains the following examples:

HTTP 触发器,使用查询字符串查找 blob 名称 (Java)HTTP trigger, look up blob name from query string (Java)

下面的示例显示了一个 Java 函数,该函数使用 HttpTrigger 注释来接收包含 blob 存储容器中某个文件的名称的一个参数。The following example shows a Java function that uses the HttpTrigger annotation to receive a parameter containing the name of a file in a blob storage container. 然后,BlobInput 注释读取该文件并将其作为 byte[] 传递给该函数。The BlobInput annotation then reads the file and passes its contents to the function as a byte[].

  @FunctionName("getBlobSizeHttp")
  @StorageAccount("Storage_Account_Connection_String")
  public HttpResponseMessage blobSize(
    @HttpTrigger(name = "req", 
      methods = {HttpMethod.GET}, 
      authLevel = AuthorizationLevel.ANONYMOUS) 
    HttpRequestMessage<Optional<String>> request,
    @BlobInput(
      name = "file", 
      dataType = "binary", 
      path = "samples-workitems/{Query.file}") 
    byte[] content,
    final ExecutionContext context) {
      // build HTTP response with size of requested blob
      return request.createResponseBuilder(HttpStatus.OK)
        .body("The size of \"" + request.getQueryParameters().get("file") + "\" is: " + content.length + " bytes")
        .build();
  }

队列触发器,接收来自队列消息的 blob 名称 (Java)Queue trigger, receive blob name from queue message (Java)

下面的示例显示了一个 Java 函数,该函数使用 QueueTrigger 注释来接收包含 blob 存储容器中某个文件的名称的一个消息。The following example shows a Java function that uses the QueueTrigger annotation to receive a message containing the name of a file in a blob storage container. 然后,BlobInput 注释读取该文件并将其作为 byte[] 传递给该函数。The BlobInput annotation then reads the file and passes its contents to the function as a byte[].

  @FunctionName("getBlobSize")
  @StorageAccount("Storage_Account_Connection_String")
  public void blobSize(
    @QueueTrigger(
      name = "filename", 
      queueName = "myqueue-items-sample") 
    String filename,
    @BlobInput(
      name = "file", 
      dataType = "binary", 
      path = "samples-workitems/{queueTrigger}") 
    byte[] content,
    final ExecutionContext context) {
      context.getLogger().info("The size of \"" + filename + "\" is: " + content.length + " bytes");
  }

Java 函数运行时库中,对其值将来自 Blob 的参数使用 @BlobInput 注释。In the Java functions runtime library, use the @BlobInput annotation on parameters whose value would come from a blob. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional<T> 的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

输入 - 特性Input - attributes

C# 类库中,使用 BlobAttributeIn C# class libraries, use the BlobAttribute.

该特性的构造函数采用 Blob 的路径,以及一个表示读取或写入的 FileAccess 参数,如以下示例中所示:The attribute's constructor takes the path to the blob and a FileAccess parameter indicating read or write, as shown in the following example:

[FunctionName("BlobInput")]
public static void Run(
    [QueueTrigger("myqueue-items")] string myQueueItem,
    [Blob("samples-workitems/{queueTrigger}", FileAccess.Read)] Stream myBlob,
    ILogger log)
{
    log.LogInformation($"BlobInput processed blob\n Name:{myQueueItem} \n Size: {myBlob.Length} bytes");
}

可以设置 Connection 属性来指定要使用的存储帐户,如以下示例中所示:You can set the Connection property to specify the storage account to use, as shown in the following example:

[FunctionName("BlobInput")]
public static void Run(
    [QueueTrigger("myqueue-items")] string myQueueItem,
    [Blob("samples-workitems/{queueTrigger}", FileAccess.Read, Connection = "StorageConnectionAppSetting")] Stream myBlob,
    ILogger log)
{
    log.LogInformation($"BlobInput processed blob\n Name:{myQueueItem} \n Size: {myBlob.Length} bytes");
}

可以使用 StorageAccount 特性在类、方法或参数级别指定存储帐户。You can use the StorageAccount attribute to specify the storage account at class, method, or parameter level. 有关详细信息,请参阅触发器 - 特性For more information, see Trigger - attributes.

输入 - 配置Input - configuration

下表解释了在 function.json 文件和 Blob 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the Blob attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 blobMust be set to blob.
directiondirection 不适用n/a 必须设置为 inMust be set to in. 用法部分中已阐述异常。Exceptions are noted in the usage section.
名称name 不适用n/a 表示函数代码中的 Blob 的变量的名称。The name of the variable that represents the blob in function code.
路径path BlobPathBlobPath Blob 的路径。The path to the blob.
连接connection ConnectionConnection 包含要用于此绑定的存储连接字符串的应用设置的名称。The name of an app setting that contains the Storage connection string to use for this binding. 如果应用设置名称以“AzureWebJobs”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." 如果将 connection 留空,函数运行时将使用名为 AzureWebJobsStorage 的应用设置中的默认存储连接字符串。If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

连接字符串必须属于某个常规用途存储帐户,而不能属于仅限 Blob 的存储帐户The connection string must be for a general-purpose storage account, not a blob-only storage account.
不适用n/a AccessAccess 表示是要读取还是写入。Indicates whether you will be reading or writing.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

输入 - 用法Input - usage

在 C# 和 C# 脚本中,可以为 blob 输入绑定使用以下参数类型:In C# and C# script, you can use the following parameter types for the blob input binding:

  • Stream
  • TextReader
  • string
  • Byte[]
  • CloudBlobContainer
  • CloudBlobDirectory
  • ICloudBlob1ICloudBlob1
  • CloudBlockBlob1CloudBlockBlob1
  • CloudPageBlob1CloudPageBlob1
  • CloudAppendBlob1CloudAppendBlob1

1 function.json 中需有 "inout" 绑定 direction 或 C# 类库中需有 FileAccess.ReadWrite1 Requires "inout" binding direction in function.json or FileAccess.ReadWrite in a C# class library.

如果尝试绑定到某个存储 SDK 类型并收到错误消息,请确保已引用正确的存储 SDK 版本If you try to bind to one of the Storage SDK types and get an error message, make sure that you have a reference to the correct Storage SDK version.

由于整个 Blob 内容都会加载到内存中,因此,只有当 Blob 较小时才建议绑定到 stringByte[]Binding to string or Byte[] is only recommended if the blob size is small, as the entire blob contents are loaded into memory. 平时,最好使用 StreamCloudBlockBlob 类型。Generally, it is preferable to use a Stream or CloudBlockBlob type. 有关详细信息,请参阅本文前文中的并发和内存使用情况For more information, see Concurrency and memory usage earlier in this article.

在 JavaScript 中,可以使用 context.bindings.<name from function.json> 访问 Blob 数据。In JavaScript, access the blob data using context.bindings.<name from function.json>.

OutputOutput

使用 blob 存储输出绑定写入 blob。Use Blob storage output bindings to write blobs.

输出 - 示例Output - example

参阅语言特定的示例:See the language-specific example:

输出 - C# 示例Output - C# example

以下示例演示使用一个 blob 触发器和两个 blob 输出绑定的 C# 函数The following example is a C# function that uses a blob trigger and two output blob bindings. sample-images 容器中创建映像 Blob 时,会触发该函数。The function is triggered by the creation of an image blob in the sample-images container. 该函数创建该映像 Blob 的小型和中型副本。It creates small and medium size copies of the image blob.

using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.WebJobs;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

[FunctionName("ResizeImage")]
public static void Run(
    [BlobTrigger("sample-images/{name}")] Stream image,
    [Blob("sample-images-sm/{name}", FileAccess.Write)] Stream imageSmall,
    [Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageMedium)
{
    IImageFormat format;

    using (Image<Rgba32> input = Image.Load(image, out format))
    {
      ResizeImage(input, imageSmall, ImageSize.Small, format);
    }

    image.Position = 0;
    using (Image<Rgba32> input = Image.Load(image, out format))
    {
      ResizeImage(input, imageMedium, ImageSize.Medium, format);
    }
}

public static void ResizeImage(Image<Rgba32> input, Stream output, ImageSize size, IImageFormat format)
{
    var dimensions = imageDimensionsTable[size];

    input.Mutate(x => x.Resize(dimensions.Item1, dimensions.Item2));
    input.Save(output, format);
}

public enum ImageSize { ExtraSmall, Small, Medium }

private static Dictionary<ImageSize, (int, int)> imageDimensionsTable = new Dictionary<ImageSize, (int, int)>() {
    { ImageSize.ExtraSmall, (320, 200) },
    { ImageSize.Small,      (640, 400) },
    { ImageSize.Medium,     (800, 600) }
};

输出 - C# 脚本示例Output - C# script example

以下示例演示 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 C# 脚本 (.csx) 代码。The following example shows blob input and output bindings in a function.json file and C# script (.csx) code that uses the bindings. 此函数创建文本 blob 的副本。The function makes a copy of a text blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

public static void Run(string myQueueItem, string myInputBlob, out string myOutputBlob, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    myOutputBlob = myInputBlob;
}

输出 - JavaScript 示例Output - JavaScript example

下面的示例展示了 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 JavaScript 代码The following example shows blob input and output bindings in a function.json file and JavaScript code that uses the bindings. 该函数创建 Blob 的副本。The function makes a copy of a blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function(context) {
    context.log('Node.js Queue trigger function processed', context.bindings.myQueueItem);
    context.bindings.myOutputBlob = context.bindings.myInputBlob;
    context.done();
};

输出 - Python 示例Output - Python example

下面的示例展示了 function.json 文件中的 blob 输入和输出绑定,以及使用这些绑定的 Python 代码The following example shows blob input and output bindings in a function.json file and Python code that uses the bindings. 该函数创建 Blob 的副本。The function makes a copy of a blob. 该函数由包含要复制的 Blob 名称的队列消息触发。The function is triggered by a queue message that contains the name of the blob to copy. 新 Blob 名为 {originalblobname}-CopyThe new blob is named {originalblobname}-Copy.

function.json 文件中,queueTrigger 元数据属性用于指定 path 属性中的 Blob 名称:In the function.json file, the queueTrigger metadata property is used to specify the blob name in the path properties:

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "queuemsg",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "inputblob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "outputblob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false,
  "scriptFile": "__init__.py"
}

配置部分解释了这些属性。The configuration section explains these properties.

下面是 Python 代码:Here's the Python code:

import logging
import azure.functions as func


def main(queuemsg: func.QueueMessage, inputblob: func.InputStream,
         outputblob: func.Out[func.InputStream]):
    logging.info('Python Queue trigger function processed %s', inputblob.name)
    outputblob.set(inputblob)

输出 - Java 示例Output - Java examples

本部分包含以下示例:This section contains the following examples:

HTTP 触发器,使用 OutputBinding (Java)HTTP trigger, using OutputBinding (Java)

下面的示例显示了一个 Java 函数,该函数使用 HttpTrigger 注释来接收包含 blob 存储容器中某个文件的名称的一个参数。The following example shows a Java function that uses the HttpTrigger annotation to receive a parameter containing the name of a file in a blob storage container. 然后,BlobInput 注释读取该文件并将其作为 byte[] 传递给该函数。The BlobInput annotation then reads the file and passes its contents to the function as a byte[]. BlobOutput 注释绑定到 OutputBinding outputItem,然后,函数使用后者来将输入 blob 的内容写入到所配置的存储容器中。The BlobOutput annotation binds to OutputBinding outputItem, which is then used by the function to write the contents of the input blob to the configured storage container.

  @FunctionName("copyBlobHttp")
  @StorageAccount("Storage_Account_Connection_String")
  public HttpResponseMessage copyBlobHttp(
    @HttpTrigger(name = "req", 
      methods = {HttpMethod.GET}, 
      authLevel = AuthorizationLevel.ANONYMOUS) 
    HttpRequestMessage<Optional<String>> request,
    @BlobInput(
      name = "file", 
      dataType = "binary", 
      path = "samples-workitems/{Query.file}") 
    byte[] content,
    @BlobOutput(
      name = "target", 
      path = "myblob/{Query.file}-CopyViaHttp")
    OutputBinding<String> outputItem,
    final ExecutionContext context) {
      // Save blob to outputItem
      outputItem.setValue(new String(content, StandardCharsets.UTF_8));

      // build HTTP response with size of requested blob
      return request.createResponseBuilder(HttpStatus.OK)
        .body("The size of \"" + request.getQueryParameters().get("file") + "\" is: " + content.length + " bytes")
        .build();
  }

队列触发器,使用函数返回值 (Java)Queue trigger, using function return value (Java)

下面的示例显示了一个 Java 函数,该函数使用 QueueTrigger 注释来接收包含 blob 存储容器中某个文件的名称的一个消息。The following example shows a Java function that uses the QueueTrigger annotation to receive a message containing the name of a file in a blob storage container. 然后,BlobInput 注释读取该文件并将其作为 byte[] 传递给该函数。The BlobInput annotation then reads the file and passes its contents to the function as a byte[]. BlobOutput 注释绑定到函数返回值,然后,运行时使用后者来将输入 blob 的内容写入到所配置的存储容器中。The BlobOutput annotation binds to the function return value, which is then used by the runtime to write the contents of the input blob to the configured storage container.

  @FunctionName("copyBlobQueueTrigger")
  @StorageAccount("Storage_Account_Connection_String")
  @BlobOutput(
    name = "target", 
    path = "myblob/{queueTrigger}-Copy")
  public String copyBlobQueue(
    @QueueTrigger(
      name = "filename", 
      dataType = "string",
      queueName = "myqueue-items") 
    String filename,
    @BlobInput(
      name = "file", 
      path = "samples-workitems/{queueTrigger}") 
    String content,
    final ExecutionContext context) {
      context.getLogger().info("The content of \"" + filename + "\" is: " + content);
      return content;
  }

Java 函数运行时库中,对其值将写入 Blob 存储中对象的函数参数使用 @BlobOutput 注释。In the Java functions runtime library, use the @BlobOutput annotation on function parameters whose value would be written to an object in blob storage. 参数类型应为 OutputBinding<T>,其中 T 是任何本机 Java 类型或者是一个 POJO。The parameter type should be OutputBinding<T>, where T is any native Java type or a POJO.

输出 - 特性Output - attributes

C# 类库中,使用 BlobAttributeIn C# class libraries, use the BlobAttribute.

该特性的构造函数采用 Blob 的路径,以及一个表示读取或写入的 FileAccess 参数,如以下示例中所示:The attribute's constructor takes the path to the blob and a FileAccess parameter indicating read or write, as shown in the following example:

[FunctionName("ResizeImage")]
public static void Run(
    [BlobTrigger("sample-images/{name}")] Stream image,
    [Blob("sample-images-md/{name}", FileAccess.Write)] Stream imageSmall)
{
    ...
}

可以设置 Connection 属性来指定要使用的存储帐户,如以下示例中所示:You can set the Connection property to specify the storage account to use, as shown in the following example:

[FunctionName("ResizeImage")]
public static void Run(
    [BlobTrigger("sample-images/{name}")] Stream image,
    [Blob("sample-images-md/{name}", FileAccess.Write, Connection = "StorageConnectionAppSetting")] Stream imageSmall)
{
    ...
}

有关完整示例,请参阅输出 - C# 示例For a complete example, see Output - C# example.

可以使用 StorageAccount 特性在类、方法或参数级别指定存储帐户。You can use the StorageAccount attribute to specify the storage account at class, method, or parameter level. 有关详细信息,请参阅触发器 - 特性For more information, see Trigger - attributes.

输出 - 配置Output - configuration

下表解释了在 function.json 文件和 Blob 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the Blob attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 blobMust be set to blob.
directiondirection 不适用n/a 对于输出绑定,必须设置为 outMust be set to out for an output binding. 用法部分中已阐述异常。Exceptions are noted in the usage section.
名称name 不适用n/a 表示函数代码中的 Blob 的变量的名称。The name of the variable that represents the blob in function code. 设置为 $return 可引用函数返回值。Set to $return to reference the function return value.
路径path BlobPathBlobPath Blob 容器的路径。The path to the blob container.
连接connection ConnectionConnection 包含要用于此绑定的存储连接字符串的应用设置的名称。The name of an app setting that contains the Storage connection string to use for this binding. 如果应用设置名称以“AzureWebJobs”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." 如果将 connection 留空,函数运行时将使用名为 AzureWebJobsStorage 的应用设置中的默认存储连接字符串。If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

连接字符串必须属于某个常规用途存储帐户,而不能属于仅限 Blob 的存储帐户The connection string must be for a general-purpose storage account, not a blob-only storage account.
不适用n/a AccessAccess 表示是要读取还是写入。Indicates whether you will be reading or writing.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

输出 - 用法Output - usage

在 C# 和 C# 脚本中,可绑定到以下类型,以编写 blob:In C# and C# script, you can bind to the following types to write blobs:

  • TextWriter
  • out string
  • out Byte[]
  • CloudBlobStream
  • Stream
  • CloudBlobContainer1CloudBlobContainer1
  • CloudBlobDirectory
  • ICloudBlob2ICloudBlob2
  • CloudBlockBlob2CloudBlockBlob2
  • CloudPageBlob2CloudPageBlob2
  • CloudAppendBlob2CloudAppendBlob2

1 function.json 中需有 "in" 绑定 direction 或 C# 类库中需有 FileAccess.Read1 Requires "in" binding direction in function.json or FileAccess.Read in a C# class library. 但是,可以使用运行时提供的容器对象来执行写入操作,例如将 Blob 上传到容器。However, you can use the container object that the runtime provides to do write operations, such as uploading blobs to the container.

2 function.json 中需有 "inout" 绑定 direction 或 C# 类库中需有 FileAccess.ReadWrite2 Requires "inout" binding direction in function.json or FileAccess.ReadWrite in a C# class library.

如果尝试绑定到某个存储 SDK 类型并收到错误消息,请确保已引用正确的存储 SDK 版本If you try to bind to one of the Storage SDK types and get an error message, make sure that you have a reference to the correct Storage SDK version.

在异步函数中,请使用返回值或 IAsyncCollector 而非 out 参数。In async functions, use the return value or IAsyncCollector instead of an out parameter.

由于整个 Blob 内容都会加载到内存中,因此,只有当 Blob 较小时才建议绑定到 stringByte[]Binding to string or Byte[] is only recommended if the blob size is small, as the entire blob contents are loaded into memory. 平时,最好使用 StreamCloudBlockBlob 类型。Generally, it is preferable to use a Stream or CloudBlockBlob type. 有关详细信息,请参阅本文前文中的并发和内存使用情况For more information, see Concurrency and memory usage earlier in this article.

在 JavaScript 中,可以使用 context.bindings.<name from function.json> 访问 Blob 数据。In JavaScript, access the blob data using context.bindings.<name from function.json>.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
BlobBlob Blob 错误代码Blob Error Codes
Blob、表、队列Blob, Table, Queue 存储错误代码Storage Error Codes
Blob、表、队列Blob, Table, Queue 故障排除Troubleshooting

后续步骤Next steps