简体   繁体   中英

Python PIL Save Image to Different “Folder” on Amazon S3

I need to save my avatar to the "avatar" folder inside my Amazon S3 bucket.

Bucket
-Static
--Misc
-Media
--Originals
--Avatars

Currently, when I create the avatar, it is saved to the Originals "folder". My goal is to save it to the Avatars "folder".

Here is my code for creating and saving the avatar

    def create_avatar(self):
    import os
    from PIL import Image
    from django.core.files.storage import default_storage as storage

    if not self.filename:
        return ""
    file_path = self.filename.name

    filename_base, filename_ext = os.path.splitext(file_path)
    thumb_file_path = "%s_thumb.jpg" % filename_base

    if storage.exists(thumb_file_path):
        return "exists"
    try:
        # resize the original image and return url path of the thumbnail
        f = storage.open(file_path, 'r')
        image = Image.open(f)
        width, height = image.size

        size = 128, 128
        image.thumbnail(size, Image.ANTIALIAS)

        f_thumb = storage.open(thumb_file_path, "w")
        image.save(f_thumb, "JPEG", quality=90)
        f_thumb.close()
        return "success"
    except:
        return "error"

I was able to save the avatar to the desired " folder " by renaming the file path with a simple python replace() function.

This did the trick if anyone else ever need to "move" a file within the S3 bucket

thumb_file_path = thumb_file_path.replace('originals/', 'avatar/')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM