| 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 |
|
This how-to contains two sections:
- Upload a file from a device application
- Receive file upload notification in a backend 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:
- Connect to IoT hub
- Get a SAS URI from IoT hub
- Upload the file to Azure storage
- Notify IoT hub of the file upload status
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-dotnet]
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);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();To upload a file to Azure storage:
-
Create a blockBlobClient object, passing a file upload URI.
-
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);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);The SDK includes this file upload sample.
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.
Backend service applications require the Microsoft.Azure.Devices NuGet package.
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 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);[!INCLUDE iot-hub-howto-connect-service-iothub-entra-dotnet]
To receive file upload notification:
- Create a CancellationToken.
- Call GetFileNotificationReceiver to create a notification receiver.
- 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);
}The SDK includes this file upload receiver sample.