django boto3:在 Amazon S3 上保存上传的文件

django boto3: save uploaded file on Amazon S3

我正在使用 boto3 在 django 项目中将文件上传到 Amazon S3。

settings.py:

...
AWS_ACCESS_KEY = 'xxxxxxxx'
AWS_SECRET_KEY = 'xxxxxxxx'
S3_BUCKET = 'xxxxx'
REGION_NAME = 'ap-southeast-1'

模板:

<form method=post action="..." enctype=multipart/form-data>
  {% csrf_token %}
  <input type="file" name="fileToUpload">
  <input type=submit value=Upload>
</form>

查看:

from mysite.settings import AWS_ACCESS_KEY, AWS_SECRET_KEY, S3_BUCKET, REGION_NAME

import boto3
from boto3.session import Session

fileToUpload = request.FILES.get('fileToUpload')
session = Session(aws_access_key_id=AWS_ACCESS_KEY,
                  aws_secret_access_key=AWS_SECRET_KEY,
                  region_name=REGION_NAME)
s3 = session.resource('s3')
fpath = os.path.dirname(os.path.realpath(__file__)) + '/abc.png'
f = open(fpath, 'rb')
s3.Bucket(S3_BUCKET).put_object(Key='uploads/test2.png', Body=f)

对于现有文件abc.png,它已正确上传到Amazon S3。但是,如何上传用户选择的文件 fileToUpload 而不是现有文件 abc.png

执行以下操作:

def upload(request):
    if request.method=='GET':
        return render(request, '<someTemplate>')
    # POST
    fileToUpload = request.FILES.get('fileToUpload')
    cloudFilename = '<someDirectory>/' + fileToUpload.name 

    session = boto3.session.Session(aws_access_key_id=AWS_ACCESS_KEY,
                                    aws_secret_access_key=AWS_SECRET_KEY)
    s3 = session.resource('s3')
    s3.Bucket(AWS_BUCKET_NAME).put_object(Key=cloudFilename, Body=fileToUpload)

    return redirect('<destinationTemplate>')