django boto3:在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>')
点赞