Azure IoT Hub 十分钟入门系列(4)-文件上传

本文主要分享一个案例:

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及容器:

img-650a9200-edd3-4ff9-92ec-679e62df0415.png

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

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

安装Node.js SDK:

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

安装过程如下图:

img-02747164-dc3c-4a9b-96ec-268f50bfa81e.png

 

 

新建文件夹,新建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, 内容随意。

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

img-cc03b613-83c6-48cb-a9ce-05b50d802904.png

 

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

node upload_to_blob.js

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

img-5ced6fde-8ccb-4300-84ac-a2b3c8a5d25f.png

 

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

img-924aeadd-97d0-4629-8c8c-fee0f35ab716.png

 


猜你喜欢

转载自blog.51cto.com/10117438/2472396
今日推荐