Uploading images get corrupted but not txt files

61 views Asked by At

I am trying to upload an image using AWS lambdas but my images get corrupted I tested with a txt file and it works great. The function checkImage is the handler

def parse_into_field_storage(fp, ctype, clength):
    fs = FieldStorage(
        fp=fp,
        environ={'REQUEST_METHOD': 'POST'},
        headers={
            'content-type': ctype,
            'content-length': clength
        },
        keep_blank_values=True
    )
    form = {}
    files = {}
    for f in fs.list:
        if f.filename:
            files.setdefault(f.name, []).append(f)
        else:
            form.setdefault(f.name, []).append(f.value)
    return form, files
  
def checkImage(event, context):
    body_file = BytesIO(bytes(event["body"], "utf-8"))
    form, files = parse_into_field_storage(
        body_file,
        event['headers']['Content-Type'],
        body_file.getbuffer().nbytes
    )

    fileitem = files['file'][0]

    print(fileitem.filename)

    # Test if the file was uploaded
    if fileitem.filename:
        fn = os.path.basename(fileitem.filename)
        open('/tmp/' + fn, 'wb').write(fileitem.file.read())
        message = 'The file "' + fn + '" was uploaded successfully'
    else:
        message = 'No file was uploaded'
    
    return {
        "statusCode": 200,
        "body": message
    }

when i print the file from python i get this

enter image description here

I used diff and the binaries are different. I am thinking that the image files get parse double or something like that I am guessing here I am doing something wrong

body_file = BytesIO(bytes(event["body"], "utf-8"))

I have tried different forms like

fp = io.BytesIO(event['body'].encode('utf-8'))

but it is basically the same.

0

There are 0 answers