Here is how I handle file uploads: which in this case happen to be images. One of the issues I fought with for awhile was that request.FILES could come in with multiple keys and I always wanted the last one.
Note: request.FILES will only contain data if:
- the request is a POST
- the request has the attribute 'enctype="multipart/form-data"'
see the Django File-uploads documentation for more details.
The Model: First there is a model with a ImageField in it: models.py
photos_dir = settings.MEDIA_ROOT + "/photos" + "/%Y/%m/%d/"
class Photo(models.Model):
image = models.ImageField(upload_to=photos_dir, null=True, blank=True, default=None)
filename = models.CharField(max_length=60, blank=True, null=True)
The View: in views.py handle the post:
from django.core.files.images import ImageFile
def upload_image( request ):
file_key=None
for file_key in sorted(request.FILES):
pass
wrapped_file = ImageFile(request.FILES[file_key])
filename = wrapped_file.name
# new photo table-row
photo = Photo()
photo.filename = filename
photo.image = request.FILES[file_key]
try:
photo.save()
except OSError:
print "Deal with this situation"
# do your stuff here.
return HttpResponse("boo", "text/html");
The Standlone Poster: Some python code to stimulate your django view.
Reference: I actually used this lib: poster.encode to 'stimulate data' to my django view.py
from poster.streaminghttp import register_openers
from poster.encode import multipart_encode
import urllib2
server = "http://localhost/"
headers = {}
# Register the streaming http handlers with urllib2
register_openers()
img="path/to/image/image.png"
data = {'media' : open( img ),
'additionalattr': 111,
}
datagen, headers = multipart_encode(data)
headers['Connection']='keep-alive'
request = urllib2.Request('%s/upload_image/' % ( server ), datagen, headers)
print urllib2.urlopen(request).read()