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

本教程的内容基于使用 IoT 中心发送云到设备的消息教程中所述的代码,介绍如何使用 IoT 中心的文件上传功能将文件上传到 Azure Blob 存储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 to upload a file to Azure blob storage. 本教程介绍如何:The tutorial 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 中心基本的设备到云的消息传送功能。The Send telemetry from a device to an IoT hub quickstart demonstrates the basic device-to-cloud messaging functionality of IoT Hub. 但是,在某些情况下,无法轻松地将设备发送的数据映射为 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 pre-processed data.

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

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

  • SimulatedDevice.js,它使用 IoT 中心提供的 SAS URI 将文件上传到存储。SimulatedDevice.js, which uploads a file to storage using a SAS URI provided by your IoT hub.
  • ReadFileUploadNotification.js,它可以接收来自 IoT 中心的文件上传通知。ReadFileUploadNotification.js, which receives file upload notifications from your IoT hub.

Note

IoT 中心通过 Azure IoT 设备 SDK 来支持许多设备平台和语言(包括 C、.NET、Javascript、Python 和 Java)。IoT Hub supports many device platforms and languages (including C, .NET, Javascript, Python, and Java) 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

  • Node.js 版本 10.0.x 或更高版本。Node.js version 10.0.x or later. 准备开发环境介绍了如何在 Windows 或 Linux 上安装本教程所用的 Node.js。Prepare your development environment describes how to install Node.js for this tutorial on either Windows or Linux.

  • 有效的 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 中心的设备应用。In this section, you create the device app to upload a file to IoT hub.

  1. 创建名为 simulateddevice 的空文件夹。Create an empty folder called simulateddevice. simulateddevice 文件夹的命令提示符处,使用以下命令创建 package.json 文件。In the simulateddevice folder, create a package.json file using the following command at your command prompt. 接受所有默认值:Accept all the defaults:

    npm init
    
  2. simulateddevice 文件夹的命令提示符处,运行下述命令以安装 azure-iot-device 设备 SDK 包和 azure-iot-device-mqtt 包:At your command prompt in the simulateddevice folder, run the following command to install the azure-iot-device Device SDK package and azure-iot-device-mqtt package:

    npm install azure-iot-device azure-iot-device-mqtt --save
    
  3. simulateddevice 文件夹中,利用文本编辑器创建 SimulatedDevice.js 文件。Using a text editor, create a SimulatedDevice.js file in the simulateddevice folder.

  4. SimulatedDevice.js 文件的开头添加以下 require 语句:Add the following require statements at the start of the SimulatedDevice.js file:

    'use strict';
    
    var fs = require('fs');
    var mqtt = require('azure-iot-device-mqtt').Mqtt;
    var clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;
    
  5. 添加 deviceconnectionstring 变量,并使用它创建一个客户端实例。Add a deviceconnectionstring variable and use it to create a Client instance. {deviceconnectionstring} 替换为在“创建 IoT 中心”部分中创建的设备的名称。Replace {deviceconnectionstring} with the name of the device you created in the Create an IoT Hub section:

    var connectionString = '{deviceconnectionstring}';
    var filename = 'myimage.png';
    

    Note

    为方便起见,代码中包含了连接字符串:这不是建议的做法,根据用例和体系结构,请考虑以更安全的方式存储此机密。For the sake of simplicity the connection string is included in the code: this is not a recommended practice and depending on your use-case and architecture you may want to consider more secure ways of storing this secret.

  6. 添加以下代码用于连接客户端:Add the following code to connect the client:

    var client = clientFromConnectionString(connectionString);
    console.log('Client connected');
    
  7. 创建一个回调,并使用 uploadToBlob 函数上传文件。Create a callback and use the uploadToBlob function to upload the file.

    fs.stat(filename, function (err, stats) {
        const rr = fs.createReadStream(filename);
    
        client.uploadToBlob(filename, rr, stats.size, function (err) {
            if (err) {
                console.error('Error uploading file: ' + err.toString());
            } else {
                console.log('File uploaded');
            }
        });
    });
    
  8. 保存并关闭 SimulatedDevice.js 文件。Save and close the SimulatedDevice.js file.

  9. 将一个图像文件复制到 simulateddevice 文件夹并将其重命名为 myimage.pngCopy an image file to the simulateddevice folder and rename it myimage.png.

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

在本文中,你将创建一项后端服务,用于从你在将遥测数据从设备发送到 IoT 中心中创建的 IoT 中心接收文件上传通知消息。In this article you create a backend 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

本部分中的操作将会创建一个 Node.js 控制台应用,用于接收来自 IoT 中心的文件上传通知消息。In this section, you create a Node.js console app that receives file upload notification messages from IoT Hub.

可以使用 IoT 中心的 iothubowner 的连接字符串完成本部分的操作。You can use the iothubowner connection string from your IoT Hub to complete this section. 可以在 Azure 门户上的“共享访问策略”边栏选项卡中找到该连接字符串。 You will find the connection string in the Azure portal on the Shared access policy blade.

  1. 创建名为 fileuploadnotification 的空文件夹。Create an empty folder called fileuploadnotification. fileuploadnotification 文件夹的命令提示符处,使用以下命令创建 package.json 文件。In the fileuploadnotification folder, create a package.json file using the following command at your command prompt. 接受所有默认值:Accept all the defaults:

    npm init
    
  2. fileuploadnotification 文件夹中的命令提示符下,运行以下命令安装 azure-iothub SDK 包:At your command prompt in the fileuploadnotification folder, run the following command to install the azure-iothub SDK package:

    npm install azure-iothub --save
    
  3. 使用文本编辑器在 fileuploadnotification 文件夹中创建 FileUploadNotification.js 文件。Using a text editor, create a FileUploadNotification.js file in the fileuploadnotification folder.

  4. FileUploadNotification.js 文件的开头添加以下 require 语句:Add the following require statements at the start of the FileUploadNotification.js file:

    'use strict';
    
    var Client = require('azure-iothub').Client;
    
  5. 添加 iothubconnectionstring 变量,并使用它创建一个客户端 实例。Add a iothubconnectionstring variable and use it to create a Client instance. {iothubconnectionstring} 占位符值替换为先前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串:Replace the {iothubconnectionstring} placeholder value with the IoT hub connection string that you copied previously in Get the IoT hub connection string:

    var connectionString = '{iothubconnectionstring}';
    

    Note

    为方便起见,代码中包含了连接字符串:这不是建议的做法,根据用例和体系结构,请考虑以更安全的方式存储此机密。For the sake of simplicity the connection string is included in the code: this is not a recommended practice and depending on your use-case and architecture you may want to consider more secure ways of storing this secret.

  6. 添加以下代码用于连接客户端:Add the following code to connect the client:

    var serviceClient = Client.fromConnectionString(connectionString);
    
  7. 打开客户端,并使用 getFileNotificationReceiver 函数接收状态更新。Open the client and use the getFileNotificationReceiver function to receive status updates.

    serviceClient.open(function (err) {
      if (err) {
        console.error('Could not connect: ' + err.message);
      } else {
        console.log('Service client connected');
        serviceClient.getFileNotificationReceiver(function receiveFileUploadNotification(err, receiver){
          if (err) {
            console.error('error getting the file notification receiver: ' + err.toString());
          } else {
            receiver.on('message', function (msg) {
              console.log('File upload from device:')
              console.log(msg.getData().toString('utf-8'));
            });
          }
        });
      }
    });
    
  8. 保存并关闭 FileUploadNotification.js 文件。Save and close the FileUploadNotification.js file.

运行应用程序Run the applications

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

fileuploadnotification 文件夹中的命令提示符下运行以下命令:At a command prompt in the fileuploadnotification folder, run the following command:

node FileUploadNotification.js

simulateddevice 文件夹中的命令提示符下运行以下命令:At a command prompt in the simulateddevice folder, run the following command:

node SimulatedDevice.js

以下屏幕截图显示 SimulatedDevice 应用的输出:The following screenshot shows the output from the SimulatedDevice app:

simulated-device 应用的输出

以下屏幕截图显示 FileUploadNotification 应用的输出:The following screenshot shows the output from the FileUploadNotification app:

read-file-upload-notification 应用的输出

可以使用门户查看所配置的存储容器中上传的文件:You can use the portal to view the uploaded file in the storage container you configured:

上传的文件

后续步骤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: