title: Serverless and uploading image from Lambda endpoint to S3
body: <p>I'm using the <a href="https://serverless.com/framework/" rel="nofollow noreferrer">Serverless framework</a> with Python. What I'm trying to accomplish is have an HTTP endpoint setup by Serverless and have that endpoint upload an image to S3. The client, Android, would upload an image from their phone and hit the endpoint with the image. I've been able to successfully upload to S3 but when I click on <code>download</code> for the image and try to open it, it appears to be corrupted.</p>
  
  <p><a href="https://i.stack.imgur.com/aYES3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aYES3.png" alt="enter image description here"></a></p>
  
  <p>I'm using the <a href="https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.upload_fileobj" rel="nofollow noreferrer">file_uploadobj</a> function and it expects a file like object as its first argument. It should be noted that the type of <code>event['body']</code> is <code>unicode</code>.</p>
  
  <p>Here is the code that I'm using to accomplish this upload.</p>
  
  <pre><code>import boto3
  
  def upload_image(event, context):
      headers, body = event['headers'] ,event['body']
      client = boto3.client('s3', region_name='us-west-2')
      filename = event['queryStringParameters']['filename']
      tmp_filename = '/tmp/' + filename
      file__ = open(tmp_filename, 'wb')
      file__.write(body)
      # file__.write(body.encode('utf-8'))
      # file__.write(body.encode('base64'))
      file__.close()
      with open(tmp_filename, 'rb') as file_data:
          client.upload_fileobj(file_data, 'bucket', filename, ExtraArgs={'ContentType': 'image/jpeg'})
      return {
          'statusCode': 200,
          'body': {'path': filename}
      }
  </code></pre>
  
  <p>Does anyone have any ideas as to what I'm doing wrong?</p>
  
  <p>I've also tried the following using <a href="https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.upload_file" rel="nofollow noreferrer">upload_file</a>.</p>
  
  <pre><code>import base64
  
  def upload_image(event, context):
      headers, body = event['headers'] ,event['body']
      client = boto3.client('s3', region_name='us-west-2')
      filename = event['queryStringParameters']['filename']
      tmp_filename = '/tmp/' + filename
      with open(tmp_filename, 'wb') as file_descriptor:
          file_descriptor.write(base64.b64decode(data))
      client.upload_file(tmp_filename, 'bucket', filename, ExtraArgs={'ContentType': 'image/jpeg'})
      return {
          'statusCode': 200,
          'body': {'path': filename}
      }
  </code></pre>