I’m hacking with a customer today who is using Python and needs to upload images to Azure IoT Hub using the File Upload API. It took us a while to figure it out and ran into a bunch of issues.
Here’s how we got it working.
After you created your IoT Hub, you need to enable file uploads on the Azure Portal. I’m sure you can do via cli as well, but I don’t have time to research that right now.
1. Go to the IoT Hub on Azure Portal
2. Click Messaging -> File Upload
3. Create a new or select an existing Standard storage account and create a container.
Make sure you create or use a Standard storage account. For some reason, file upload doesn’t work with Premium storage accounts. I’m following up with the team on that.
4. Turn on “Receive notifications for uploaded files”
5. Click Save
Follow the instructions here for getting the Python SDK on your machine. If you are using Linux, then you will have to compile it yourself. If you are using Windows you can use pip.
You don’t have to open the sample to run it, but if you want to look at the code it is in the azure-iot-sdk-python repo device/samples/iothub_client_sample_class.py.
Navigate to the folder devices/samples/ and run the following.
Replace [device connection string] with the device’s connection string that you copied in step 1 above.
If everything is setup correctly, you will see the following message:
Here’s the meat of the code for this sample.
And here’s the code that calls that method:
If you want to upload files, you need to read them into memory first like this:
If you see the following error…you will need to open up the sample file in your IDE and add a comma after ‘size’ like this:
If you see the following error…it could mean one of two things:
1. You don’t have a storage account associated with your IoT Hub.
2. You are using a “Premium Storage” Account. Solution: Change your storage account to Standard Storage.
3. You aren’t using the correct container access type. It must be a container with “container” access type, like this:
Note: File upload appears to now work with any container access type.
The error is apparently due to the Premium Storage account not allowing ACLs. See the “warn” statement below.
You can use Azure Storage Explorer to view the uploaded file.
If you go to the storage account that you associated with IoT Hub in Azure Portal, you’ll see an Open in Storage Explorer button.
Drill down to your container and you’ll see your file.
If you want a direct URL to the file it will look like this:
You’ll need to replace your storage name, container name and then build the rest of the path based on the parameters you passed to the upload method when you uploaded the file.