I have successfully uploaded an image using the following code:
views.py
from django.conf.urls.defaults import *
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import template
from django.template import RequestContext
from mysite.uploadr.forms import UploadFileForm
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.handle_uploaded_file(request.FILES['file'])
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form}, context_instance=RequestContext(request))
forms.py
from django import forms
from settings import MEDIA_ROOT
class UploadFileForm(forms.Form):
title = forms.CharField(max_length = 50)
file = forms.FileField()
def handle_uploaded_file(self,file):
#print type(file), "file.name=",file.name
#print dir(file)
destination = open(MEDIA_ROOT + '/images/'+file.name, 'wb+')
for chunk in file.chunks():
destination.write(chunk)
I'd like to go one step further and associate an image with the user who is uploading. I've seen a few examples and have taken a liking to the technique in this post: http://stackoverflow.com/questions/3348013/django-image-file-uploads.
I noticed that their code uses save() and cleaned_data. Is it not necessary to iterate thru the chunks and write to the destination folder like the examples in the documentation? Do I have to use cleaned_data? Just trying to figure out the most efficient means of uploading files, I 've seen so many different ways of doing this. Your help you be greatly appreciated.