Uploading attachment using REST API

I am trying to upload an image file as an attachment to a submission using the instructions in this documentation. The post request is successful, however when I download and open the image attachment I encounter this error:

I used the python sudo code below. And the post request is successful however the file format seems to be wrong. I have also tried the 'Content-Type': 'image/jpeg' header with the same result.

import requests
from PIL import Image

img = Image.open('{path of image}')
binary_data = img.tobytes()

headers = {
	'Content-Type': '*/*',
	'Authorization': 'Bearer {}'.format(token)
}

url = 'https://private-3b1543-odkcentral.apiary-mock.com/v1/projects/projectId/forms/xmlFormId/submissions/instanceId/attachments/filename'
request = request.post(url, data=binary_data, headers=headers)
print(request.status_code)

Has anyone tried uploading an attachment using the API? How did you do it and made the file format correct?

You can try with this code to send an attachment in a submission:

# Uploading an attachment

# Libraries
import requests
import json

# Modify headers
headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'image/jpeg'
}

# File name of the attachment
filename = "1234567891011.jpg"

# Send "imagefile.jpg" in the attachment field "1234567891011.jpg"
with open("imagefile.jpg", "rb") as f:
    # Request POST to send attachment
    # Instance ID
    instance_id = "uuid:12f345dc-67a8-9101-ab11-213141e5d1bdb"
    response = requests.post(f'{base_url}/v1/projects/{project_id}/forms/{xml_form_id}/submissions/{instance_id}/attachments/{filename}',
                           data=f, headers=headers)
    response = response.json()
    print(json.dumps(response, indent=4))
1 Like