使用Django將上傳的圖像保存到S3

[英]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:

我正在嘗試使用boto將圖像保存到S3中。它確實保存了一個文件,但是看起來並沒有正確地保存它。如果我嘗試在S3中打開文件,它只顯示一個損壞的圖像圖標。下面是我使用的代碼:

# 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.

但這也不管用。有什么明顯的東西我不在這里嗎?我知道django-storage有一個boto后端,但是由於這個模型的復雜性,我不想使用帶有django-storage的表單。

1 个解决方案

#1


1  

You should use django-storages which uses boto internally.

你應該使用在內部使用boto的django-storages。

You can either swap the default FileSystemStorage, or create a new storage instance and manually save files. Based on your code example I guess you really want to go with the first option.

您可以交換默認的文件系統存儲,或者創建一個新的存儲實例並手動保存文件。根據您的代碼示例,我猜您確實希望使用第一個選項。

Please consider using django's Form instead of directly accessing the request.

請考慮使用django的表單而不是直接訪問請求。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/03/13/725059f9d802fd645875f7043108a6ce.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com