| title | Upload files from devices to Azure IoT Hub (Node) | |||
|---|---|---|---|---|
| titleSuffix | Azure IoT Hub | |||
| description | How to upload files from a device to the cloud using Azure IoT device SDK for Node.js. Uploaded files are stored in an Azure storage blob container. | |||
| author | SoniaLopezBravo | |||
| ms.author | sonialopez | |||
| ms.service | azure-iot-hub | |||
| ms.devlang | nodejs | |||
| ms.topic | include | |||
| ms.date | 07/01/2024 | |||
| ms.custom |
|
This article describes how to use the Azure IoT SDK for Node.js to create a device app to upload a file and backend service application receive file upload notification.
This section describes how to upload a file from a device to an IoT hub using the azure-iot-device package in the Azure IoT SDK for Node.js.
Run this command to install the azure-iot-device device SDK, the azure-iot-device-mqtt, and the @azure/storage-blob packages on your development machine:
npm install azure-iot-device azure-iot-device-mqtt @azure/storage-blob --save
The azure-iot-device package contains objects that interface with IoT devices.
Follow this procedure to upload a file from a device to IoT hub:
- Connect the device to IoT Hub
- Get a Blob shared access signature (SAS) token from IoT Hub
- Upload the file to Azure Storage
- Send file upload status notification to IoT hub
Create Client, Protocol, errors, and path modules using the installed packages.
const Protocol = require('azure-iot-device-mqtt').Mqtt;
const errors = require('azure-iot-common').errors;
const path = require('path');A device app can authenticate with IoT Hub using the following methods:
- X.509 certificate
- Shared access key
[!INCLUDE iot-hub-howto-auth-device-cert-node]
The Client object supports these protocols:
AmqpHttp- When usingHttp, theClientinstance checks for messages from IoT Hub infrequently (a minimum of every 25 minutes).MqttMqttWsAmqpWs
Install needed transport protocols on your development machine.
For example, this command installs the Amqp protocol:
npm install azure-iot-device-amqp --save
For more information about the differences between MQTT, AMQP, and HTTPS support, see Cloud-to-device communications guidance and Choose a communication protocol.
Create a Client object using the installed package.
For example:
const Client = require('azure-iot-device').Client;Create a Protocol object using an installed transport package.
This example assigns the AMQP protocol:
const Protocol = require('azure-iot-device-amqp').Amqp;Call fromConnectionString to supply device connection parameters:
- connStr - The device connection string.
- transportCtor - The transport protocol.
This example uses the Amqp transport protocol:
const deviceConnectionString = "{IoT hub device connection string}"
const Protocol = require('azure-iot-device-mqtt').Amqp;
let client = Client.fromConnectionString(deviceConnectionString, Protocol);Use the open method to open connection between an IoT device and IoT Hub.
For example:
client.open(function(err) {
if (err) {
console.error('error connecting to hub: ' + err);
process.exit(1);
}
})Use getBlobSharedAccessSignature to get the linked storage account SAS token from IoT hub.
For example:
// make sure you set these environment variables prior to running the sample.
const localFilePath = process.env.PATH_TO_FILE;
const storageBlobName = path.basename(localFilePath);
const blobInfo = await client.getBlobSharedAccessSignature(storageBlobName);
if (!blobInfo) {
throw new errors.ArgumentError('Invalid upload parameters');
}To upload a file from a device to IoT hub:
- Create a stream pipeline
- Construct the blob URL
- Create a BlockBlobClient for file upload to Blob Storage
- Call uploadFile to upload the file to Blob Storage
- Call notifyBlobUploadStatus to notify IoT hub that the upload succeeded or failed
For example:
// Open the pipeline
const pipeline = newPipeline(new AnonymousCredential(), {
retryOptions: { maxTries: 4 },
telemetry: { value: 'HighLevelSample V1.0.0' }, // Customized telemetry string
keepAliveOptions: { enable: false }
});
// Construct the blob URL
const { hostName, containerName, blobName, sasToken } = blobInfo;
const blobUrl = `https://${hostName}/${containerName}/${blobName}${sasToken}`;
// Create the BlockBlobClient for file upload to Blob Storage
const blobClient = new BlockBlobClient(blobUrl, pipeline);
// Setup blank status notification arguments to be filled in on success/failure
let isSuccess;
let statusCode;
let statusDescription;
const uploadStatus = await blobClient.uploadFile(localFilePath);
console.log('uploadStreamToBlockBlob success');
try {
const uploadStatus = await blobClient.uploadFile(localFilePath);
console.log('uploadStreamToBlockBlob success');
// Save successful status notification arguments
isSuccess = true;
statusCode = uploadStatus._response.status;
statusDescription = uploadStatus._response.bodyAsText;
// Notify IoT hub of upload to blob status (success)
console.log('notifyBlobUploadStatus success');
}
catch (err) {
isSuccess = false;
statusCode = err.code;
statusDescription = err.message;
console.log('notifyBlobUploadStatus failed');
console.log(err);
}
// Send file upload status notification to IoT hub
await client.notifyBlobUploadStatus(blobInfo.correlationId, isSuccess, statusCode, statusDescription);You can upload a local file to blob storage from a computer
const deviceClient = Client.fromConnectionString(deviceConnectionString, Protocol);
uploadToBlob(localFilePath, deviceClient)
.catch((err) => {
console.log(err);
})
.finally(() => {
process.exit();
});The SDK includes an upload to blob advanced sample.
This section describes how to receive file upload notifications in a backend application.
The ServiceClient class contains methods that services can use to receive file upload notifications.
Run this command to install azure-iothub on your development machine:
npm install azure-iothub --save
You can connect a backend service to IoT Hub using the following methods:
- Shared access policy
- Microsoft Entra
[!INCLUDE iot-authentication-service-connection-string.md]
Use fromConnectionString to connect to IoT hub.
To upload a file from a device, your service needs the service connect permission. By default, every IoT Hub is created with a shared access policy named service that grants this permission.
As a parameter to CreateFromConnectionString, supply the service shared access policy connection string. For more information about shared access policies, see Control access to IoT Hub with shared access signatures.
var Client = require('azure-iothub').Client;
var connectionString = '{IoT hub shared access policy connection string}';
var client = Client.fromConnectionString(connectionString);[!INCLUDE iot-hub-howto-connect-service-iothub-entra-node]
To create a file upload notification callback receiver:
- Call getFileNotificationReceiver. Supply the name of a file upload callback method that is called when notification messages are received.
- Process file upload notifications in the callback method.
This example sets up a receiveFileUploadNotification notification callback receiver. The receiver interprets the file upload status information and prints a status message to the console.
//Set up the receiveFileUploadNotification notification message callback receiver
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'));
receiver.complete(msg, function (err) {
if (err) {
console.error('Could not finish the upload: ' + err.message);
} else {
console.log('Upload complete');
}
});
});
}The SDK includes a file upload sample.