| title | Upload files from devices to Azure IoT Hub (Java) | |||||
|---|---|---|---|---|---|---|
| titleSuffix | Azure IoT Hub | |||||
| description | How to upload files from a device to the cloud using Azure IoT device SDK for Java. Uploaded files are stored in an Azure storage blob container. | |||||
| author | SoniaLopezBravo | |||||
| ms.author | sonialopez | |||||
| ms.service | azure-iot-hub | |||||
| ms.devlang | java | |||||
| 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 from the Azure IoT SDK for Java.
Follow this procedure to upload a file from a device to IoT hub:
- Connect the device to IoT Hub
- Get a SAS URI from IoT hub
- Upload the file to Azure Storage
- Send file upload status notification to IoT hub
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-java]
File upload operations always use HTTPS, but DeviceClient can define the IotHubClientProtocol for other services like telemetry, device method, and device twin.
IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;Instantiate the DeviceClient to connect to the device using the device primary connection string.
String connString = "{IoT hub connection string}";
DeviceClient client = new DeviceClient(connString, protocol);Call getFileUploadSasUri to obtain a FileUploadSasUriResponse object.
FileUploadSasUriResponse includes these methods and return values. The return values can be passed to file upload methods.
| Method | Return value |
|---|---|
getCorrelationId() |
Correlation ID |
getContainerName() |
Container name |
getBlobName() |
Blob name |
getBlobUri() |
Blob URI |
For example:
FileUploadSasUriResponse sasUriResponse = client.getFileUploadSasUri(new FileUploadSasUriRequest(file.getName()));
System.out.println("Successfully got SAS URI from IoT hub");
System.out.println("Correlation Id: " + sasUriResponse.getCorrelationId());
System.out.println("Container name: " + sasUriResponse.getContainerName());
System.out.println("Blob name: " + sasUriResponse.getBlobName());
System.out.println("Blob Uri: " + sasUriResponse.getBlobUri());Pass the blob URI endpoint to BlobClientBuilder.buildclient to create the BlobClient object.
BlobClient blobClient =
new BlobClientBuilder()
.endpoint(sasUriResponse.getBlobUri().toString())
.buildClient();Call uploadFromFile to upload the file to Blob Storage.
String fullFileName = "Path of the file to upload";
blobClient.uploadFromFile(fullFileName);Send an upload status notification to IoT hub after a file upload attempt.
Create a FileUploadCompletionNotification object. Pass the correlationId and isSuccess file upload success status. Pass an isSuccess true value when file upload was successful, false when not.
FileUploadCompletionNotification must be called even when the file upload fails. IoT hub has a fixed number of SAS URI allowed to be active at any given time. Once you're done with the file upload, you should free your SAS URI so that other SAS URI can be generated. If a SAS URI isn't freed through this API, then it frees itself eventually based on how long SAS URIs are configured to live on an IoT hub.
This example passes a successful status.
FileUploadCompletionNotification completionNotification = new FileUploadCompletionNotification(sasUriResponse.getCorrelationId(), true);
client.completeFileUpload(completionNotification);Free the client resources.
client.closeNow();This section describes how to receive a file upload notification in a backend application.
The ServiceClient class contains methods that services can use to receive file upload notifications.
Add these import statements to use the Azure IoT Java SDK and exception handler.
import com.microsoft.azure.sdk.iot.service.*;
import java.io.IOException;
import java.net.URISyntaxException;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 IotHubServiceClientProtocol to define the application-layer protocol used by the service client to communicate with an IoT Hub.
IotHubServiceClientProtocol only accepts the AMQPS or AMQPS_WS enum.
private static final IotHubServiceClientProtocol protocol =
IotHubServiceClientProtocol.AMQPS;Create the ServiceClient object, supplying the IoT Hub connection string and protocol.
To upload a file on a device to IoT Hub, 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 the ServiceClient constructor, supply the service shared access policy. For more information about shared access policies, see Control access to IoT Hub with shared access signatures.
String iotHubConnectionString = "HostName=xxxxx.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxx";
private static final ServiceClient serviceClient (iotHubConnectionString, protocol);Open the AMQP sender connection. This method creates the connection between the application and IoT Hub.
serviceClient.open();[!INCLUDE iot-hub-howto-connect-service-iothub-entra-java]
To check for file upload status:
- Create a getFileUploadNotificationReceiver object.
- Use open to connect to IoT hub.
- Call receive to check for the file upload status. This method returns a fileUploadNotification object. If an upload notice is received, you can view upload status fields using fileUploadNotification methods.
For example:
FileUploadNotificationReceiver receiver = serviceClient.getFileUploadNotificationReceiver();
receiver.open();
FileUploadNotification fileUploadNotification = receiver.receive(2000);
if (fileUploadNotification != null)
{
System.out.println("File Upload notification received");
System.out.println("Device Id : " + fileUploadNotification.getDeviceId());
System.out.println("Blob Uri: " + fileUploadNotification.getBlobUri());
System.out.println("Blob Name: " + fileUploadNotification.getBlobName());
System.out.println("Last Updated : " + fileUploadNotification.getLastUpdatedTimeDate());
System.out.println("Blob Size (Bytes): " + fileUploadNotification.getBlobSizeInBytes());
System.out.println("Enqueued Time: " + fileUploadNotification.getEnqueuedTimeUtcDate());
}
else
{
System.out.println("No file upload notification");
}
// Close the receiver object
receiver.close();There are two Java file upload samples.