Get the App
SLTechnology News&Howtos  ›  Servers  › 

Azure IoT Hub 10-minute getting started Series (4)-File upload

Shulou Source: shulou.com Published: 2022-06-03 07:22:05 09月30日 Update

This article mainly shares a case: upload files to IoTHub through Device SDK within 10 minutes. This article mainly has the following contents: 1. Know where files are stored in IoT Hub 2. Use Node.js Device SDK to upload TXT files 3. View files uploaded by IOT devices in Storage

Bilibili video explanation: https://www.bilibili.com/video/av90224073/

Picture and text content:

Reference to this case: https://docs.azure.cn/zh-cn/iot-hub/iot-hub-node-node-file-upload

1. The files uploaded to Azure IoT Hub by the device via Device SDK are stored in Storage. You need to configure the Storage and container for storing the files in advance:

two。 Upload files using Node.js SDK

Download and install Node.js http://nodejs.cn/

Install Node.js SDK:

Npm install azure-iot-device azure-iot-device-mqtt-save

The installation process is shown below:

Create a new folder, create a new upload_to_blob.js, and copy the following sample code into 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);}});})

Use the following command to create a package.json file. Accept all default values:

Npm init

Create a log.txt in a folder with arbitrary content.

At this point, the folder should look like the following figure:

Execute the following command to run the client code:

Node upload_to_blob.js

The program prompt is as follows, which indicates that the file was uploaded successfully:

Enter the Azure Storage container and check the upload result:

Tags: Files contents folders storage code commands containers devices success graphics and text clients clients file downloads cases examples programs results so far video process Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Technology Microsoft NVidia Linux