本文主要分享一个案例:

10分钟内通过Device SDK上传文件到IoTHub

 

本文主要有如下内容:

1. 了解IoT Hub中文件存储在了哪里

2. 使用Node.js Device SDK 上传TXT文件

3. 在Storage中查看IOT设备上传的文件

 

视频讲解:

请观看B站视频:https://www.bilibili.com/video/av90224073/

或本站视频(内容相同,二选一即可)

 

图文内容:

本案例参考:https://docs.azure.cn/zh-cn/iot-hub/iot-hub-node-node-file-upload

 

1. 设备经Device SDK 上传到Azure IoT Hub的文件存储到了Storage中,需提前配置好存储文件用的Storage及容器:

2. 使用Node.js SDK上传文件

下载安装Node.js http://nodejs.cn/

安装Node.js SDK:

npm install azure-iot-device azure-iot-device-mqtt --save

安装过程如下图:

 

 

新建文件夹,新建upload_to_blob.js,将下列示例代码拷入upload_to_blob.js中

'use strict';

var Protocol = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var fs = require('fs');

var connectionString = 'YOUR DEIVCE CONNECT STRING';
if (!connectionString) {
  console.log('Please set the DEVICE_CONNECTION_STRING environment variable.');
  process.exit(-1);
}

var filePath = 'log.txt';

var client = Client.fromConnectionString(connectionString, Protocol);

fs.stat(filePath, function (err, fileStats) {
  if (err) {
    console.error('could not read file: ' + err.toString());
    process.exit(-1);
  } else {
    var fileStream = fs.createReadStream(filePath);

    client.uploadToBlob('testblob.txt', fileStream, fileStats.size, function (err) {
      fileStream.destroy();
      if (err) {
        console.error('error uploading file: ' + err.constructor.name + ': ' + err.message);
        process.exit(-1);
      } else {
        console.log('Upload successful');
        process.exit(0);
      }
    });
  }
});

 

使用以下命令创建 package.json 文件。 接受所有默认值:

npm init

 

在文件夹中创建 log.txt, 内容随意。

至此,文件夹应该如下图所示:

 

执行如下命令,运行客户端代码:

node upload_to_blob.js

程序提示如下,表示成功上传文件:

 

进入Azure Storage 容器中,检查上传结果:

 

Azure IoT Hub 十分钟入门系列,其他文章,请参见:
  1. (视频)Azure IoT Hub 十分钟入门系列 (1)- 10分钟带你了解Azure IoT Hub 并创建IoT Hub
  2. (视频)Azure IoT Hub 十分钟入门系列 (2)- 使用模拟设备发送设备到云(d2c)的消息
  3. (视频)Azure IoT Hub 十分钟入门系列 (3)- 使用消息路由将原始设备数据记录存档
  4. (视频)Azure IoT Hub 十分钟入门系列 (4)- 实现从设备上传日志文件/图片到 Azure Storage
  5. (视频)Azure IoT Hub 十分钟入门系列 (5)- 10分钟实现云到设备的消息(direct method)
  6. (视频)Azure IoT Hub 十分钟入门系列 (6)- 了解设备孪生(device twin)
  7. (视频)Azure IoT Hub 十分钟入门系列 (7)- 小结