Sep-30-2020, 07:16 PM
I am trying to upload images using aws lambdas, I am testing locally with serverless offline. When I upload an image it gets corrupted, but when I upload a txt file it works ok. So I guess it has to do something with the encoding
import json import os from cgi import FieldStorage from io import BytesIO 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 }checkImage is the main handler that. I have tried different approaches but the result is the same. I am guessing this is the problem
body_file = BytesIO(bytes(event["body"], "utf-8"))Maybe I shoul use another encoding.