Django的存储在S3中上传文件

Django的存储在S3中上传文件

本文介绍了Django的存储在S3中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类,它暴露了POST端点的API消费者的使用Django的REST框架。

在code应该接收文件的上传,然后将其上传到S3。该文件被正确地上载到Django应用( file_obj.length 返回实际文件大小),和在对象在S3创建的。然而,在S3中的文件大小为零。如果我登录的返回 file_obj.read()为空为好。

什么是错的?

 从django.conf导入设置

从rest_framework.views进口APIView
从rest_framework.response进口回复
从rest_framework.parsers进口FileUploadParser
从boto.s3.connection进口S3Connection
从boto.s3.key导入密钥

从.models进口上传
从.serializers进口UploadSerializer


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

    高清后期(个体经营,要求,形式=无):
        file_obj = request.FILES ['文件']

        上传=上传(用户= request.user,文件= file_obj)
        upload.save()

        康恩= S3Connection(settings.AWS_ACCESS_KEY,settings.AWS_SECRET_KEY)
        K =密钥(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())

        串行= UploadSerializer(上传)

        返回响应(serializer.data,状态= 201)
 

解决方案

难道事情是读取文件对象已经,保存方法,也许你的上传类,你需要寻求回到起点?

  file_obj.seek(0)
 

I have this class that exposes a POST endpoint to an API consumer using Django REST framework.

The code is supposed to receive a file upload, and then upload it to 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. However, the file size in S3 is zero. If I log the return of file_obj.read() it is empty as well.

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)
解决方案

Is it possible that something is reading the file object already, perhaps your Upload class save method, and you need to seek back to the beginning?

file_obj.seek(0)

这篇关于Django的存储在S3中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:34