微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Django Rest Framework将上传进度栏与s3存储桶上的上传同步

如何解决如何使用Django Rest Framework将上传进度栏与s3存储桶上的上传同步

我正在使用REST API(使用Django Rest Framework)。我正在尝试通过向发布的端点发送发布请求来上传视频。

问题

视频确实已上传到s3存储桶,但是无论我上传的是大文件上传进度仅在几秒钟内显示100%。

为什么会这样,我该如何解决呢?

PS :以前我是在本地存储上上传,并且上传进度正常。 我正在使用React。

解决方法

首先,请确保您已安装以下库:boto3==1.14.53botocore==1.17.53s3transfer==0.3.3django-storages==1.10

settings.py:

INSTALLED_APPS = [
 
    'storages',]


AWS_ACCESS_KEY_ID = 'your-key-id'
AWS_SECRET_ACCESS_KEY = 'your-secret-key'
AWS_STORAGE_BUCKET_NAME = 'your-bucket-name'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',}
DEFAULT_FILE_STORAGE = 'your_project-name.storage_backends.MediaStorage'

MEDIA_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN

#File upload setting
BASE_URL = 'http://example.com'
FILE_UPLOAD_PERMISSIONS = 0o640
DATA_UPLOAD_MAX_MEMORY_SIZE = 500024288000

然后在storage_backends文件所在的项目文件夹中创建一个settings.py python文件。

storage_backends.py:

import os
from tempfile import SpooledTemporaryFile

from storages.backends.s3boto3 import S3Boto3Storage


class MediaStorage(S3Boto3Storage):
    bucket_name = 'your-bucket-name'
    file_overwrite = False

    def _save(self,name,content):
        """
        We create a clone of the content file as when this is passed to
        boto3 it wrongly closes the file upon upload where as the storage
        backend expects it to still be open
        """
        # Seek our content back to the start
        content.seek(0,os.SEEK_SET)

        # Create a temporary file that will write to disk after a specified
        # size. This file will be automatically deleted when closed by
        # boto3 or after exiting the `with` statement if the boto3 is fixed
        with SpooledTemporaryFile() as content_autoclose:
            # Write our original content into our copy that will be closed by boto3
            content_autoclose.write(content.read())

            # Upload the object which will auto close the
            # content_autoclose instance
            return super(MediaStorage,self)._save(name,content_autoclose)


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。