Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save uploaded image to S3 with Django

I'm attempting to save an image to S3 using boto. It does save a file, but it doesn't appear to save it correctly. If I try to open the file in S3, it just shows a broken image icon. Here's the code I'm using:

# Get and verify the file
file = request.FILES['file']
try:
    img = Image.open(file)
except:
    return api.error(400)

# Determine a filename
filename = file.name

# Upload to AWS and register
s3 = boto.connect_s3(aws_access_key_id=settings.AWS_KEY_ID,
                aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
bucket = s3.get_bucket(settings.AWS_BUCKET)
f = bucket.new_key(filename)
f.set_contents_from_file(file)

I've also tried replacing the last line with:

f.set_contents_from_string(file.read())

But that didn't work either. Is there something obvious that I'm missing here? I'm aware django-storages has a boto backend, but because of complexity with this model, I do not want to use forms with django-storages.

like image 742
Luke Sapan Avatar asked Mar 13 '15 15:03

Luke Sapan


1 Answers

Incase you don't want to go for django-storages and just want to upload few files to s3 rather then all the files then below is the code:

import boto3
file = request.FILES['upload']
s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
bucket = s3.Bucket('bucket-name')
bucket.put_object(Key=filename, Body=file)
like image 136
Dhruvil Amin Avatar answered Sep 27 '22 17:09

Dhruvil Amin