Api image upload error

Alexei a year ago

Hi
I'm trying to upload image to a device, using API and I make the POST request:
url = f"{API_URL}/{device_id}/image" response = requests.post(url, headers=headers, json=payload, verify=False)

As a payload I use:
payload = { "deviceImage": base64_image_with_prefix}

file is 300kb size, but I constantly face with:

Receive: Failed to upload image. Status code: 415
Response: HTTP 415 Unsupported Media Type - NotSupportedException (... < OverrideFilter:49 < ...)
Image upload failed.

Tried to use: png, jpg, jpeg - nothing helped.
In API documentation there's nothing described and related to upload images for the devices. Forum messages do not solve the issue too

Adriano Miranda a year ago

Hi Alexei,

You can try something like this:

headers = {
    'Content-Type': 'image/jpeg',  # or 'image/png', depending on the image format
    # Add other necessary headers here
}

# Set the path to your image file
image_path = '/path/to/your/image.jpg'

# Define the correct API endpoint URL (/api/devices)
url = f"{API_URL}/devices/{device_id}/image"

# Open the image file in binary mode and send the POST request
with open(image_path, 'rb') as image_file:
    response = requests.post(url, headers=headers, data=image_file)

# anything else from your code...
Alexei a year ago

Thanks. In may case worked replaced header from "Content-Type": "application/json"
to "Content-Type": "image/jpeg"

In general process looks like:


    def upload_image(device_id, image_path):
    
     headers = {
        "Authorization": f"Bearer {TOKEN}",
        "Content-Type": "image/jpeg",
        "Accept": "application/json",
    }

    # Convert the image to base64 with MIME type prefix
    base64_image_with_prefix = convert_image_to_base64(image_path)
    
    # Prepare the JSON payload
    payload = {
        "deviceImage": base64_image_with_prefix
    }
    
    # Make the POST request
    url = f"{API_URL}/{device_id}/image"
    response = requests.post(url, headers=headers, json=payload)

    # Handle response
    if response.status_code == 200:
        print("Image uploaded successfully!")
        return True
    else:
        print(f"Failed to upload image. Status code: {response.status_code}")
        print(f"Response: {response.text}")
        return False```