簡體   English   中英

如何使用 s3 作為存儲在 django 中自動顯示媒體文件?

[英]How do I make media files display automatically in django using s3 as storage?

我像這樣配置了我的 s3 設置:

DEFAULT_FILE_STORAGE = 'Bonychicken.storage_backends.MediaStorage'
AWS_STORAGE_BUCKET_NAME = 'bonychicken'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_ACCESS_KEY_ID = '<my access key id>'
AWS_SECRET_ACCESS_KEY = '<my secret access key>'
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com"
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = None
STATIC_URL = '/static/'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
MEDIA_ROOT = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
AWS_IS_GZIPPED = True
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

我的存儲類是:

from storages.backends.s3boto3 import S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    bucket_name = 'bonychicken'
    location = 'media'
    file_overwrite = False

我為已安裝的應用程序添加了storages ,並且還安裝了boto3

CORS 配置是:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

block public access已被關閉。 IAM用戶對存儲桶具有權限。

問題是,每當我上傳文件時,它都會上傳到我的 s3 存儲桶,但它不會顯示在 html 頁面上。 嘗試從源代碼訪問圖像 url 會產生:

<Error>
    <Code>AccessDenied</Code>
    <Message>Access Denied</Message>
    <RequestId><random letters here></RequestId>
    <HostId>
        <random letters here>
    </HostId>
</Error>

但是,如果我轉到我的存儲桶設置並選擇actions並在標記媒體文件后單擊make public ,一切都會開始工作。 這意味着對於上傳的每張圖片,我必須一遍又一遍地標記和重復。

我該如何解決這個問題?

我認為您應該更改 AWS 設置中的默認 ACL,如文檔中所示。

只需將AWS_DEFAULT_ACL設置為AWS_DEFAULT_ACL='public-read'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM