简体   繁体   English

Django在S3中存储上传的文件

[英]Django store uploaded file in S3

I have this class that exposes a POST endpoint to an API consumer using Django REST framework. 我有这个类使用Django REST框架将POST端点暴露给API使用者。

The code is supposed to receive a file upload, and then upload it to S3. 该代码应该接收文件上传,然后将其上传到S3。 The file is uploaded correctly to the Django app ( file_obj.length returns the actual file size), and the object is created in S3. 文件正确上传到Django应用程序( file_obj.length返回实际文件大小),并在S3中创建对象。 However, the file size in S3 is zero. 但是,S3中的文件大小为零。 If I log the return of file_obj.read() it is empty as well. 如果我记录file_obj.read()的返回,它也是空的。

What is wrong? 怎么了?

from django.conf import settings

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import FileUploadParser
from boto.s3.connection import S3Connection
from boto.s3.key import Key

from .models import Upload
from .serializers import UploadSerializer


class UploadList(APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request, format=None):
        file_obj = request.FILES['file']

        upload = Upload(user=request.user, file=file_obj)
        upload.save()

        conn = S3Connection(settings.AWS_ACCESS_KEY, settings.AWS_SECRET_KEY)
        k = Key(conn.get_bucket(settings.AWS_S3_BUCKET))
        k.key = 'upls/%s/%s.png' % (request.user.id, upload.key)
        k.set_contents_from_string(file_obj.read())

        serializer = UploadSerializer(upload)

        return Response(serializer.data, status=201)

有可能某些东西正在读取文件对象,也许你的上传类保存方法,你需要回头看?

file_obj.seek(0)

You can use django storage 您可以使用django存储

pip install django-storages

http://django-storages.readthedocs.org/en/latest/ http://django-storages.readthedocs.org/en/latest/

In your model, 在你的模型中,

def upload_image_to(instance, filename):
    import os
    from django.utils.timezone import now
    filename_base, filename_ext = os.path.splitext(filename)
    return 'posts/%s/%s' % (
        now().strftime("%Y%m%d"),
        instance.id
    )


image = models.ImageField(upload_to=upload_image_to, editable=True, null=True, blank=True)

In your settings, 在您的设置中,

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_S3_SECURE_URLS = False       # use http instead of https
AWS_QUERYSTRING_AUTH = False     # don't add complex authentication-related query parameters for requests

AWS_S3_ACCESS_KEY_ID = 'KEY'     # enter your access key id
AWS_S3_SECRET_ACCESS_KEY = 'KEY' # enter your secret access key
AWS_STORAGE_BUCKET_NAME = 'name.media'


INSTALLED_APPS = (
    ...
    'storages',

)

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

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