0

I need to download a file from an url and use a put request to upload it somewhere else

Download is done with

r=requests.get(image_url, auth=HTTPBasicAuth( user , password))
header_content_type = r.headers.get('content-type')
fileType = header_content_type.split('/')[-1]
content_type = header_content_type.split(';')[-1]
file_extension = fileType.split(';',1)[0]
file_name = file_id+'.' + file_extension
open('downloads/' + file_name , 'wb').write(r.content)

which works fine and stores the file locally in the downloads folder. I can open the image with any image viewer and it works fine.

the put request needs to look like

{ "data":"gsddfgdsfg...(base64) ", "filename":"example2.txt", "contentType":"plain/text" }

I have tried to do it like following

def build_step_attachment_json(path, filename, contentype):
    with open(path+filename) as f:
        encoded = base64.b64encode(f.read())
    return '{  "data":"'+ encoded + '", "filename":"' + filename +'", "contentType":" '+ contentype + '" }'

but it fails with: "UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 44: character maps to "

Jörg Lang
  • 171
  • 1
  • 1
  • 8
  • I have updated the method to ```python def build_step_attachment_json(path, filename, contentype): image = open(path+filename, 'rb') image_read = image.read() image_64_encode = base64.encodestring(image_read) return '{ "data":"'+ image_64_encode + '", "filename":"' + filename +'", "contentType":" '+ contentype + '" }' ``` But error is now: TypeError: must be str, not bytes – Jörg Lang Jul 17 '19 at 18:33
  • Found the answer by following https://stackoverflow.com/questions/37225035/serialize-in-json-a-base64-encoded-data – Jörg Lang Jul 17 '19 at 20:08

0 Answers0