我是编程和Django的初学者,所以我很感激初学者可以帮助他们的帮助!
我正在按照教程展示如何使用Boto库将图像上传到Amazon S3帐户,但我认为它适用于旧版本的Django(我在1.1.2和Python 2.65上)并且有些变化。我收到一个错误: 异常类型:TypeError 异常值:'InMemoryUploadedFile'对象是不可取消的
我的代码是:
Models.py:
from django.db import models
from django.contrib.auth.models import User
from django import forms
from datetime import datetime
class PhotoUrl(models.Model):
url = models.CharField(max_length=128)
uploaded = models.DateTimeField()
def save(self):
self.uploaded = datetime.now()
models.Model.save(self)
views.py:
import mimetypes
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django import forms
from django.conf import settings
from boto.s3.connection import S3Connection
from boto.s3.key import Key
def awsdemo(request):
def store_in_s3(filename, content):
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
b = conn.create_bucket('almacmillan-hark')
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_strong(content)
k.set_acl("public-read")
photos = PhotoUrl.objects.all().order_by("-uploaded")
if not request.method == "POST":
f = UploadForm()
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
f = UploadForm(request.POST, request.FILES)
if not f.is_valid():
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
file = request.FILES['file']
filename = file.name
content = file['content']
store_in_s3(filename, content)
p = PhotoUrl(url="http://almacmillan-hark.s3.amazonaws.com/" + filename)
p.save()
photos = PhotoUrl.objects.all().order_by("-uploaded")
return render_to_response('awsdemo.html', {'form':f, 'photos':photos})
urls.py:
(r'^awsdemo/$', 'harkproject.s3app.views.awsdemo'),
awsdemo.html:
<div class="form">
<strong>{{form.file.label}}</strong>
<form method="POST" action ="." enctype="multipart/form-data">
{{form.file}}<br/>
<input type="submit" value="Upload">
</form>
</div>
我真的很感激帮助。我希望我提供了足够的代码。
亲切的问候 AL
答案 0 :(得分:7)
我认为你的问题就在这一行:
content = file['content']
来自Django docs:
FILES中的每个值都是一个UploadedFile对象,包含以下属性:
- read(num_bytes = None) - 从文件中读取一些字节。
- name - 上传文件的名称。
- size - 上传文件的大小(以字节为单位)。
- chunks(chunk_size = None) - 生成顺序数据块的生成器。
请改为尝试:
content = file.read()
答案 1 :(得分:0)
你试过Django Storages吗?这样,您只需将存储后端(在本例中为s3boto)指定为默认存储后端,或将其作为参数提供给FileField或ImageField类。