2

I am trying to upload the image to my bucket on AWS S3. Earlier it was working fine. But now the uploaded image is having the size 0 byte. I have tried rolling back to previous versions of my project on GitHub. But nothing seems to work now. I am stuck on this issue for 2 days now.

def upload_to_aws(local_file, bucket_name, s3_file):
    s3 = boto3.client('s3', aws_access_key_id=BaseConfig.AWS_ACCESS_KEY_ID,
                      aws_secret_access_key=BaseConfig.AWS_SECRET_ACCESS_KEY)
    s3.upload_fileobj(local_file, bucket_name, s3_file)
    file_url = '%s/%s/%s' % (s3.meta.endpoint_url, bucket_name, s3_file)
    return file_url
from werkzeug.datastructures import FileStorage

parser = reqparse.RequestParser()
parser.add_argument('image', 
  type=FileStorage,
  required=True, 
  help='image is required',
  location='files'
)

class Classifier(Resource):
  def post(self):
    data = Classifier.parser.parse_args()
    image = data["image"]
    key_name = "some-key-name"
    upload_to_aws(image, BaseConfig.BUCKET_NAME, key_name)
    return {message: "uploaded successfully"}, 200
زوہیب خان
  • 390
  • 1
  • 7
  • 21

1 Answers1

1

The upload_fileobj() function will upload a file-like object to S3. You would pass it a file object returned from an open() command.

If the image variable contains a filename, you should be using upload_file() instead.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • My image variable contains the file and I have tried open() command. It show the following error. TypeError: expected str, bytes or os.PathLike object, not FileStorage. – زوہیب خان May 26 '21 at 11:36
  • In that case, you would use `put_object(Body=image)`. – John Rotenstein May 26 '21 at 11:54
  • using put_object(Body=image) shows the exact same error, as the one in the first comment. – زوہیب خان May 26 '21 at 12:02
  • `FileStorage` apparently has something to do with Flask? Whatever it is, it is not the "actual image data". – John Rotenstein May 26 '21 at 12:09
  • Yes, I'm using flask-restful. Is there any way I could convert this file, and upload it then? It was working fine earlier. I don't know what is going on now. – زوہیب خان May 26 '21 at 12:13
  • This might help: [How to upload a file from a Flask's HTML form to an S3 bucket using python?](https://stackoverflow.com/a/60239208/174777) It's using a slightly different way of using boto3, but the equivalent in your code would be `s3.put_object(...,Body=image.read())`. See if that works! – John Rotenstein May 26 '21 at 22:12