使用 IoT 中心 (.NET) 将文件从设备上传到云Upload files from your device to the cloud with IoT Hub (.NET)

本教程的内容基于 Send Cloud-to-Device messages with IoT Hub(使用 IoT 中心发送云到设备的消息)教程中所述的代码,演示如何使用 IoT 中心的文件上传功能。This tutorial builds on the code in the Send Cloud-to-Device messages with IoT Hub tutorial to show you how to use the file upload capabilities of IoT Hub. 其中了说明了如何:It shows you how to:

  • 安全地为设备提供用于上传文件的 Azure Blob URI。Securely provide a device with an Azure blob URI for uploading a file.
  • 使用 IoT 中心文件上传通知在应用后端中触发对文件的处理。Use the IoT Hub file upload notifications to trigger processing the file in your app back end.

从设备将遥测数据发送到 IoT 中心快速入门和使用 IoT 中心发送云到设备的消息教程介绍了 IoT 中心提供的基本的设备到云和云到设备的消息传送功能。The Send telemetry from a device to an IoT hub quickstart and Send cloud-to-device messages with IoT Hub tutorial show the basic device-to-cloud and cloud-to-device messaging functionality of IoT Hub. 使用 IoT 中心配置消息路由教程介绍了一种在 Azure Blob 存储中可靠存储设备到云消息的方法。The Configure Message Routing with IoT Hub tutorial describes a way to reliably store device-to-cloud messages in Azure blob storage. 但是,在某些情况下,无法轻松地将设备发送的数据映射为 IoT 中心接受的相对较小的设备到云消息。However, in some scenarios you cannot easily map the data your devices send into the relatively small device-to-cloud messages that IoT Hub accepts. 例如:For example:

  • 包含图像的大型文件Large files that contain images
  • 视频Videos
  • 以高频率采样的振动数据Vibration data sampled at high frequency
  • 某种形式的预处理数据Some form of preprocessed data

通常使用 Hadoop 堆栈等工具在云中批处理这些文件。These files are typically batch processed in the cloud using tools such as the Hadoop stack. 需要从设备上传文件时,仍可以使用 IoT 中心的安全性和可靠性。When you need to upload files from a device, you can still use the security and reliability of IoT Hub.

在本教程结束时,会运行 2 个 .NET 控制台应用:At the end of this tutorial you run two .NET console apps:

  • SimulatedDeviceSimulatedDevice. 此应用使用 IoT 中心提供的 SAS URI 将文件上传到存储。This app uploads a file to storage using a SAS URI provided by your IoT hub. 它是修改版的应用,在使用 IoT 中心发送云到设备消息教程中创建。It is a modified version of the app created in the Send cloud-to-device messages with IoT Hub tutorial.

  • ReadFileUploadNotificationReadFileUploadNotification. 此应用接收来自 IoT 中心的文件上传通知。This app receives file upload notifications from your IoT hub.

备注

IoT 中心通过 Azure IoT 设备 SDK 来支持许多设备平台和语言(包括 C、Java、Python 和 Javascript)。IoT Hub supports many device platforms and languages, including C, Java, Python, and Javascript, through Azure IoT device SDKs. 有关如何将设备连接到 Azure IoT 中心的分步说明,请参阅 Azure IoT 开发人员中心Refer to the Azure IoT Developer Center for step-by-step instructions on how to connect your device to Azure IoT Hub.

先决条件Prerequisites

  • Visual StudioVisual Studio
  • 有效的 Azure 帐户。An active Azure account. (如果没有帐户,只需几分钟即可创建一个试用帐户。)(If you don't have an account, you can create a trial account in just a couple of minutes.)
  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本文中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this article uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

将 Azure 存储帐户关联到 IoT 中心Associate an Azure Storage account to IoT Hub

由于模拟设备应用将文件上传到 Blob,因此必须拥有与 IoT 中心关联的 Azure 存储帐户。Because the simulated device app uploads a file to a blob, you must have an Azure Storage account associated with your IoT hub. 将 Azure 存储帐户与 IoT 中心相关联时,IoT 中心会生成一个 SAS URI。When you associate an Azure Storage account with an IoT hub, the IoT hub generates a SAS URI. 设备可以使用此 SAS URI 安全地将文件上传到 Blob 容器。A device can use this SAS URI to securely upload a file to a blob container. IoT 中心服务和设备 SDK 协调生成 SAS URI 的过程,并使其可供设备用来上传文件。The IoT Hub service and the device SDKs coordinate the process that generates the SAS URI and makes it available to a device to use to upload a file.

按照使用 Azure 门户配置文件上传中的说明进行操作。Follow the instructions in Configure file uploads using the Azure portal. 确保有一个 Blob 容器与 IoT 中心关联并且已启用文件通知。Make sure that a blob container is associated with your IoT hub and that file notifications are enabled.

在门户中启用文件通知

从设备应用上传文件Upload a file from a device app

在本部分中,会修改在使用 IoT 中心发送云到设备消息中创建的设备应用,以接收来自 IoT 中心的云到设备消息。In this section, you modify the device app you created in Send cloud-to-device messages with IoT Hub to receive cloud-to-device messages from the IoT hub.

  1. 在 Visual Studio 的“解决方案资源管理器”中,右键单击“SimulatedDevice”项目,然后选择“添加” > “现有项”。 In Visual Studio Solution Explorer, right-click the SimulatedDevice project, and select Add > Existing Item. 找到某个图像文件并将它包含在项目中。Find an image file and include it in your project. 本教程假设图像名称为 image.jpgThis tutorial assumes the image is named image.jpg.

  2. 右键单击该图像,并选择“属性”。 Right-click the image, and then select Properties. 确保“复制到输出目录”设置为“始终复制”。Make sure that Copy to Output Directory is set to Copy always.

    显示更新“复制到输出目录”图像属性的位置

  3. Program.cs 文件的顶部添加以下语句:In the Program.cs file, add the following statements at the top of the file:

    using System.IO;
    
  4. 将以下方法添加到 Program 类:Add the following method to the Program class:

    private static async void SendToBlobAsync()
    {
        string fileName = "image.jpg";
        Console.WriteLine("Uploading file: {0}", fileName);
        var watch = System.Diagnostics.Stopwatch.StartNew();
    
        using (var sourceData = new FileStream(@"image.jpg", FileMode.Open))
        {
            await deviceClient.UploadToBlobAsync(fileName, sourceData);
        }
    
        watch.Stop();
        Console.WriteLine("Time to upload file: {0}ms\n", watch.ElapsedMilliseconds);
    }
    

    UploadToBlobAsync 方法获取要上传的文件的文件名与流源,并处理上传到存储的任务。The UploadToBlobAsync method takes in the file name and stream source of the file to be uploaded and handles the upload to storage. 控制台应用会显示上传文件所需的时间。The console app displays the time it takes to upload the file.

  5. Main 方法中的 Console.ReadLine() 前面添加以下行:Add the following line in the Main method, right before Console.ReadLine():

    SendToBlobAsync();
    

备注

为简单起见,本教程不实现任何重试策略。For simplicity's sake, this tutorial does not implement any retry policy. 在生产代码中,应该按暂时性故障处理中所述实施重试策略(例如指数退避)。In production code, you should implement retry policies, such as exponential backoff, as suggested in Transient fault handling.

获取 IoT 中心连接字符串Get the IoT hub connection string

在本文中,你将创建一项后端服务,用于从你在将遥测数据从设备发送到 IoT 中心中创建的 IoT 中心接收文件上传通知消息。In this article, you create a back-end service to receive file upload notification messages from the IoT hub you created in Send telemetry from a device to an IoT hub. 若要接收文件上传通知消息,服务需要“服务连接”权限。 To receive file upload notification messages, your service needs the service connect permission. 默认情况下,每个 IoT 中心都使用名为 service 的共享访问策略创建,该策略授予此权限。By default, every IoT Hub is created with a shared access policy named service that grants this permission.

若要获取 service 策略的 IoT 中心连接字符串,请执行以下步骤:To get the IoT Hub connection string for the service policy, follow these steps:

  1. Azure 门户中,选择“资源组” 。In the Azure portal, select Resource groups. 选择中心所在的资源组,然后从资源列表中选择中心。Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. 在 IoT 中心的左侧窗格中,选择“共享访问策略” 。On the left-side pane of your IoT hub, select Shared access policies.

  3. 从策略列表中选择“service” 策略。From the list of policies, select the service policy.

  4. 在“共享访问密钥” 下,选择“连接字符串 - 主密钥” 所对应的“复制”图标并保存该值。Under Shared access keys, select the copy icon for the Connection string -- primary key and save the value.

    显示如何检索连接字符串

有关 IoT 中心共享访问策略和权限的详细信息,请参阅访问控制和权限For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

接收文件上传通知Receive a file upload notification

在本部分中,会编写一个 .NET 控制台应用,用于接收来自 IoT 中心的文件上传通知消息。In this section, you write a .NET console app that receives file upload notification messages from IoT Hub.

  1. 在当前的 Visual Studio 解决方案中,选择“文件” > “新建” > “项目” 。In the current Visual Studio solution, select File > New > Project. 在“创建新项目”中,选择“控制台应用(.NET Framework)”,然后选择“下一步” 。In Create a new project, select Console App (.NET Framework), and then select Next.

  2. 将项目命名为 ReadFileUploadNotificationName the project ReadFileUploadNotification. 在“解决方案”下选择“添加到解决方案”。 Under Solution, select Add to solution. 选择“创建” 来创建项目。Select Create to create the project.

    在 Visual Studio 中配置 ReadFileUploadNotification 项目

  3. 在“解决方案资源管理器”中,右键单击 ReadFileUploadNotification 项目,然后选择“管理 NuGet 包”。 In Solution Explorer, right-click the ReadFileUploadNotification project, and select Manage NuGet Packages.

  4. 在“NuGet 包管理器”中选择“浏览”。 In NuGet Package Manager, select Browse. 搜索并选择 Microsoft.Azure.Devices,然后选择“安装”。 Search for and select Microsoft.Azure.Devices, and then select Install.

    此步骤下载、安装 Azure IoT 服务 SDK NuGet 包并在 ReadFileUploadNotification 项目中添加对它的引用。This step downloads, installs, and adds a reference to the Azure IoT service SDK NuGet package in the ReadFileUploadNotification project.

  5. 在此项目的 Program.cs 文件的顶部添加以下语句:In the Program.cs file for this project, add the following statement at the top of the file:

    using Microsoft.Azure.Devices;
    
  6. 将以下字段添加到 Program 类。Add the following fields to the Program class. {iot hub connection string} 占位符值替换为先前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串:Replace the {iot hub connection string} placeholder value with the IoT hub connection string that you copied previously in Get the IoT hub connection string:

    static ServiceClient serviceClient;
    static string connectionString = "{iot hub connection string}";
    
  7. 将以下方法添加到 Program 类:Add the following method to the Program class:

    private async static void ReceiveFileUploadNotificationAsync()
    {
        var notificationReceiver = serviceClient.GetFileNotificationReceiver();
    
        Console.WriteLine("\nReceiving file upload notification from service");
        while (true)
        {
            var fileUploadNotification = await notificationReceiver.ReceiveAsync();
            if (fileUploadNotification == null) continue;
    
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Received file upload notification: {0}", 
              string.Join(", ", fileUploadNotification.BlobName));
            Console.ResetColor();
    
            await notificationReceiver.CompleteAsync(fileUploadNotification);
        }
    }
    

    请注意,此接收模式与用于从设备应用接收云到设备消息的模式相同。Note this receive pattern is the same one used to receive cloud-to-device messages from the device app.

  8. 最后,在 Main 方法中添加以下行:Finally, add the following lines to the Main method:

    Console.WriteLine("Receive file upload notifications\n");
    serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
    ReceiveFileUploadNotificationAsync();
    Console.WriteLine("Press Enter to exit\n");
    Console.ReadLine();
    

运行应用程序Run the applications

现在,已准备就绪,可以运行应用程序了。Now you are ready to run the applications.

  1. 在解决方案资源管理器中,右键单击解决方案并选择“设置启动项目”。 In Solutions Explorer, right-click your solution, and select Set StartUp Projects.

  2. 在“常用属性” > “启动项目”中,选择“多个启动项目”,然后针对 ReadFileUploadNotificationSimulatedDevice 选择“启动”操作。 In Common Properties > Startup Project, select Multiple startup projects, then select the Start action for ReadFileUploadNotification and SimulatedDevice. 选择“确定” 保存更改。Select OK to save your changes.

  3. F5Press F5. 这两个应用程序应该都会启动。Both applications should start. 将在其中一个控制台应用中看到上传已完成,同时还会看到另一个控制台应用收到的上传通知消息。You should see the upload completed in one console app and the upload notification message received by the other console app. 可使用 Azure 门户或 Visual Studio 服务器资源管理器检查 Azure 存储帐户中是否存在上传的文件。You can use the Azure portal or Visual Studio Server Explorer to check for the presence of the uploaded file in your Azure Storage account.

    显示输出屏幕的屏幕截图

后续步骤Next steps

在本教程中,已学习了如何使用 IoT 中心的文件上传功能来简化从设备进行的文件上传。In this tutorial, you learned how to use the file upload capabilities of IoT Hub to simplify file uploads from devices. 可以使用以下文章继续探索 IoT 中心功能和方案:You can continue to explore IoT hub features and scenarios with the following articles:

若要进一步探索 IoT 中心的功能,请参阅:To further explore the capabilities of IoT Hub, see: