Skip to content

Latest commit

 

History

History
191 lines (130 loc) · 8.35 KB

File metadata and controls

191 lines (130 loc) · 8.35 KB
title Upload files from devices to Azure IoT Hub (.NET)
titleSuffix Azure IoT Hub
description How to upload files from a device to the cloud using Azure IoT device SDK for .NET. Uploaded files are stored in an Azure storage blob container.
author SoniaLopezBravo
ms.author sonialopez
ms.service azure-iot-hub
ms.devlang csharp
ms.topic include
ms.date 12/12/2024
ms.custom
mqtt
devx-track-csharp
devx-track-dotnet
sfi-ropc-nochange

Overview

This how-to contains two sections:

  • Upload a file from a device application
  • Receive file upload notification in a backend application

Upload a file from a device application

This section describes how to upload a file from a device to an IoT hub using the DeviceClient class in the Azure IoT SDK for .NET.

Follow this procedure to upload a file from a device to IoT hub:

  1. Connect to IoT hub
  2. Get a SAS URI from IoT hub
  3. Upload the file to Azure storage
  4. Notify IoT hub of the file upload status

Connect a device to IoT Hub

A device app can authenticate with IoT Hub using the following methods:

  • X.509 certificate
  • Shared access key

Authenticate using an X.509 certificate

[!INCLUDE iot-hub-howto-auth-device-cert-dotnet]

Authenticate using a shared access key

Call CreateFromConnectionString to connect to the device. Pass the device primary connection string.

AMQP is the default transport protocol.

static string connectionString = "{device primary connection string}";
deviceClient = DeviceClient.CreateFromConnectionString(connectionString);

Get a SAS URI from IoT hub

Call GetFileUploadSasUriAsync to get file upload details. The SAS URI is used in the next step to upload a file from a device to Blob Storage.

const string filePath = "TestPayload.txt";
using var fileStreamSource = new FileStream(filePath, FileMode.Open);
var fileName = Path.GetFileName(fileStreamSource.Name);
var fileUploadSasUriRequest = new FileUploadSasUriRequest
{
    BlobName = fileName
};

FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest, System.Threading.CancellationToken cancellationToken = default);
Uri uploadUri = sasUri.GetBlobUri();

Upload a file to Azure storage

To upload a file to Azure storage:

  1. Create a blockBlobClient object, passing a file upload URI.

  2. Use the UploadAsync method to upload a file to Blob Storage, passing the SAS URI. You can optionally add Blob upload options and cancellation token parameters.

The Azure Blob client always uses HTTPS as the protocol to upload the file to Azure Storage.

In this example, BlockBlobClient is passed the SAS URI to create an Azure Storage block Blob client and uploads the file:

var blockBlobClient = new BlockBlobClient(uploadUri);
await blockBlobClient.UploadAsync(fileStreamSource, null, null);

Notify IoT hub of the file upload status

Use CompleteFileUploadAsync to notify IoT hub that the device client completed the upload, passing a FileUploadCompletionNotification object. The IsSuccess flag indicates whether or not the upload was successful. After being notified, IoT hub will release resources associated with the upload (the SAS URI).

If file upload notifications are enabled, IoT hub sends a file upload notification message to backend services that are configured for file upload notification.

var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
{
    // Mandatory. Must be the same value as the correlation id returned in the sas uri response
    CorrelationId = sasUri.CorrelationId,

    // Mandatory. Will be present when service client receives this file upload notification
    IsSuccess = true,

    // Optional, user defined status code. Will be present when service client receives this file upload notification
    StatusCode = 200,

    // Optional, user-defined status description. Will be present when service client receives this file upload notification
    StatusDescription = "Success"
};

await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

SDK file upload sample

The SDK includes this file upload sample.

Receive a file upload notification in a backend application

You can create a backend service to receive file upload notification messages from IoT hub.

The ServiceClient class contains methods that services can use to receive file upload notifications.

Add service NuGet Package

Backend service applications require the Microsoft.Azure.Devices NuGet package.

Connect to IoT hub

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]

Connect using a shared access policy

Connect a backend application to a device using CreateFromConnectionString. Your application needs service connect permission. Supply this shared access policy connection string as a parameter to fromConnectionString. For more information about shared access policies, see Control access to IoT Hub with shared access signatures.

For example:

using Microsoft.Azure.Devices;
static ServiceClient serviceClient;
static string connectionString = "{Shared access policy connection string}";
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

Connect using Microsoft Entra

[!INCLUDE iot-hub-howto-connect-service-iothub-entra-dotnet]

Receive file upload notification

To receive file upload notification:

  1. Create a CancellationToken.
  2. Call GetFileNotificationReceiver to create a notification receiver.
  3. Use a loop with ReceiveAsync to wait for the file upload notification.

For example:

// Define the cancellation token
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

// Create a notification receiver
var notificationReceiver = serviceClient.GetFileNotificationReceiver();
Console.WriteLine("\nReceiving file upload notification from service");

// Check for file upload notifications
while (true)
{
    var fileUploadNotification = await notificationReceiver.ReceiveAsync(token);
    if (fileUploadNotification == null) continue;
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Received file upload notification: {0}", 
        string.Join(", ", fileUploadNotification.BlobName));
    Console.ResetColor();
    await notificationReceiver.CompleteAsync(fileUploadNotification);
}

SDK file upload receiver sample

The SDK includes this file upload receiver sample.