I'm trying to save binary POST data to an ImageFile field - so far
with no satisfying success.
I can't seem to convince the client (Flex based image editor) to send
binary data as correct "multipart/form-data"; I only have the option
to send as raw binary data or with POST variables.
My view function happily receives the binary data, and it looks ok. As
far as I understand things, if the uploaded data was sent correctly as
multipart-form-data, Django would create an InMemoryUploadFile object
and pass it in request.FILES. I could use this code to save the image
then:
model_instance.image.save("%s.jpg" % img_id, request.FILES
['user_img'], True)
What sensible approach could I use to update/save the image with
binary POST data? I do not want to create a temporary file, though.
I just don't seem to have enough in-depth Django knowledge to find a
satisfying solution...
Thanks!
Markus
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
from django.core.files.uploadedfile import SimpleUploadedFile
def set_user_image(request, img_id):
"""
set/update a user's image
"""
if not request.user.is_authenticated():
return HttpResponse(status=403)
# get the profile for the logged on user
profile = get_object_or_404(GenericProfile, user = request.user)
# instantiate an uploaded file to be passed to the model
upfile = SimpleUploadedFile("%s.jpg" % img_id,
request._raw_post_data,
"image/jpeg")
# update the user profile
profile.image.save("%s.jpg" % img_id, upfile, True)
return HttpResponse()
This code lacks important functionality though, e.g. check if the file
is a valid JPEG image, check if img_id is valid, etc.
So basically all you have to do is create a new SimpleUploadFile
object and initialize it with the raw POST data. Of course the client
has to use the correct format; in Flex, I did something like this:
var req:URLRequest = new URLRequest(baseURL + "setimage/" + _field);
req.method = "POST";
req.data = jpData; /* this is the ByteArray containing JPEG data */
req.contentType = "image/jpeg";
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, uploadOK);
loader.addEventListener(IOErrorEvent.IO_ERROR, uploadFault);
loader.load(req);
To all you Django gurus out there: is this a sensible approach?
Thanks and happy holidays!
Markus