简体   繁体   English

Django在上传到Amazon S3存储桶之前更改图像名称

[英]Django changes image name before uploading to Amazon S3 bucket

I am using Django-1.7 and have a field of type ImageField in a model to store the image link to the AWS S3 bucket 我正在使用Django-1.7并且在模型中有一个类型为ImageField的字段来存储到AWS S3存储桶的图像链接

cover_image = models.ImageField(upload_to='s3_bucket_name/', null=True, blank=True)

In the settins.py file, I have settins.py文件中,我有

MEDIA_ROOT = 'url_to_aws_s3_bucket'
MEDIA_URL = 'url_to_aws_s3_bucket'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_STORAGE_BUCKET_NAME = 'bucket_name'
AWS_ACCESS_KEY_ID = 's3_access_key'
AWS_SECRET_ACCESS_KEY = 's3_secret_key'

The problem is when I upload an image with @ character in its name, Django removes all instances of @ before uploading the image to Amazon S3 bucket. 问题是,当我上传名称中带有@字符的图像时,Django在将图像上传到Amazon S3存储桶之前会删除@所有实例。

How do I keep the name of the image file intact? 如何保持图像文件的名称完整?

You can try to inherit from S3BotoStorage and redefine get_available_name method: 您可以尝试从S3BotoStorage继承并重新定义get_available_name方法:

class MyS3BotoStorage(S3BotoStorage):
    def get_available_name(self, name):
        return name

Instead of passing a string as upload_to='s3_bucket_name/' , I passed the function 我没有传递字符串作为upload_to='s3_bucket_name/' ,而是传递了函数

def change_filename(instance, filename):
    return 'bucket_name/' + filename

# inside the model class
cover_image = models.ImageField(upload_to=change_filename, null=True, blank=True)

and now it works fine. 现在工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Django模型表单调整图像大小,然后再将其上传到Amazon S3存储桶 - Resize an image, from Django model form before uploading it to amazon s3 bucket AWS S3:图像正在上传到存储桶,但文件未显示在heroku Django中 - AWS S3: image is uploading to bucket but file is not showing in heroku Django 将文件上传到S3存储桶-Python Django - Uploading files to S3 bucket - Python Django 如何在 django 中上传到 s3 之前压缩图像? - how to compress the image before uploading to s3 in django? 从heroku网站上将文件上传到Amazon s3存储桶时出现问题 - Problems uploading files to Amazon s3 bucket from a website on heroku 在将上传的文件发送到亚马逊 s3 存储桶之前,如何在 Django 上重命名上传的文件? - How can I rename an uploaded file on Django before sending it to amazon s3 bucket? 使用 flask Python 将文件上传到 Amazon S3 存储桶 - Uploading files to an Amazon S3 bucket using flask Python Python Flask-如何在将图像上传到Amazon s3之前读取图像的大小 - Python Flask- how can I read the size of an image before uploading it to Amazon s3 Django 多张图片上传到S3 Bucket - Django multiple image upload to S3 Bucket TypeError使用BOTO Library将图像文件上传到Django中的Amazon S3 - TypeError uploading image file to Amazon S3 in Django using BOTO Library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM