How to post a entity instance with a image attribute by web-api?

Hi .all,

I have a doctor entity with a attribute named photo as type of image . how to register the photo with web api?

I try to do first to post an base64 encode image to api/fileResources, but got this:
{“httpStatus”:“Internal Server Error”,“httpStatusCode”:500,“status”:“ERROR”,“message”:“Current request is not a multipart request”}

with mutipart request, also got erro.

Hi @linxd

I created a photo attribute and added it to a test program on play version 40. When I uploaded the image to the photo attribute, it created the following request:

  1. POST request to DHIS 2 Demo - Sierra Leone, and the body contained form-data with the following:
------WebKitFormBoundaryloudxKWGvEt0BClE

Content-Disposition: form-data; name="file"; filename="chrome_6KhSzeiW13.png"
Content-Type: image/png

------WebKitFormBoundaryloudxKWGvEt0BClE--
  1. The JSON response included the id of the image:

Finally, when I enrolled the TE in the program, the following POST request was made to /api/40/tracker?async=false, and the JSON payload was:

{"trackedEntities":[{"enrollments":[{"occurredAt":"2023-09-25","enrolledAt":"2023-09-25","program":"S7d0wGcxUGL","orgUnit":"ImspTQPwCqd","attributes":[{"attribute":"lZGmxYbs97q","value":"2127137"},{"attribute":"w75KJ2mc4zz","value":"TestingFirst"},{"attribute":"zDhUuAYrxNC","value":"Testinglast"},{"attribute":"c8U82T7gsLW","value":"Y0rnoxv7MhZ"}],"status":"ACTIVE","events":[]}],"orgUnit":"ImspTQPwCqd","trackedEntityType":"nEenWmSyUEp"}]}

You can see that the attribute with id c8U82T7gsLW above has the value Y0rnoxv7MhZ which is the id of the image.

So to post an image attribute, you first need to upload it to the fileResources endpoint and get the id of the image from the response, and then using the tracker endpoint, in the attributes field use the attribute id and give it the value the id of the image you uploaded.

I hope this helps! Thanks!

Thanks. I will try to do this in java .

1 Like

Thanks, good luck! Good to know that you are developing apps using Java and integrating with the DHIS2 web API.

I am using mirth connect to get data from other system or db into DHIS2.
create message in transformer :slight_smile:

var boundary = ‘----------’ + UUIDGenerator.getUUID();
var bi =[…]; // image byte array
var entity = org.apache.http.entity.mime.MultipartEntityBuilder.create()
.setBoundary(boundary)
.addBinaryBody(“file”,bi ,org.apache.http.entity.ContentType.IMAGE_PNG,“photo.png”)
.build();

var bos = new java.io.ByteArrayOutputStream();
entity.writeTo(bos);
msg = FileUtil.encode(bos.toByteArray());

http sender :
post content-type: multipart/form-data;boundary=${boundary}
content: ${message.encodedData}

1 Like