When trying to send multipart/form-data in httpClient post method as data param, we getting errors like {'detail': u'Missing boundary in multipart.'}
Got the solution with system.net.httpPost
after spending some time on this, here is the below code
import mimetypes
from StringIO import StringIO
def upload_images(text_field, files):
url = 'https://example.com/upload'
token = "someRandomKey"
boundary = '----WebKitFormBoundary' + str(system.date.toMillis(system.date.now()))
content_type = 'multipart/form-data; boundary={}'.format(boundary)
body = StringIO()
# Add the text field to the body
body.write('--{}\r\n'.format(boundary))
body.write('Content-Disposition: form-data; name="text_field"\r\n\r\n')
body.write(text_field + '\r\n')
# Add each file to the body
for file_path in files:
with open(file_path, 'rb') as file:
file_data = file.read()
filename = file_path.split('/')[-1]
body.write('--{}\r\n'.format(boundary))
body.write('Content-Disposition: form-data; name="files"; filename="{}"\r\n'.format(filename))
body.write('Content-Type: {}\r\n\r\n'.format(mimetypes.guess_type(file_path)[0] or 'application/octet-stream'))
body.write(file_data)
body.write('\r\n')
# End the body with the boundary
body.write('--{}--\r\n'.format(boundary))
# Prepare the request
headers = {
'Accept': 'application/json',
'X-API-Key': token,
'Content-Type': content_type
}
response = system.net.httpPost(url, contentType=content_type, postData=str(body.getvalue()), headerValues=headers)
return response
# Example usage
text_field = "sample text"
files = ['C:\\xxxxx_xxx-xx-xx_xx-xx-xx_x.jpg', 'C:\\xxxxx_xxx-xx-xx_xx-xx-xx_x.png']
response = upload_images(text_field, files)
print(response)