I trying to restful server that one can upload image, By use django-piston I can put,get,post information restfully but don't know how to upload image.
-
sorry about lack of detail. I need to create restful webservice that can do upload image and return id and url of image by use django-piston , Is it possible to do that? – vernomcrp May 15 '10 at 08:45
4 Answers
On the one hand, yes. If you have the image data, it's possible to send it via post to a handler that knows how to handle it; if you do it right, it should, theoretically, be available in request.FILES to your handler. Simple HTTP.
On the other hand, no. In order to do an AJAX upload like this, you would have to somehow get the image data without the user actually submitting a form. This is why "ajax upload forms" are so difficult to implement, and usually use tricks like hidden iframes to do their stuff.
To the best of my knowledge, only Firefox and its gecko kin allow this kind of access to a file field's binary content, via the File object's getAsBinary() method.

- 6,805
- 4
- 33
- 39
You can certainly do the POST. The file(s) will be available in the request.FILES (piston won't get in the way of this).
In order to do the PUT, we'll have to make some changes to piston to support the x-method-override header. That's what I do to allow PUT and DEL from flash. ( Don't forget to add the header when you do the POST to make it get interpreted as a PUT )
Here's some example middleware:
class x_http_methodoverride_middleware():
def process_request(self, request):
if 'HTTP_X_HTTP_METHODOVERRIDE' in request.META:
newMethod = request.META['HTTP_X_HTTP_METHODOVERRIDE']
if 'PUT' == newMethod.upper():
request.method = 'PUT'
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST
if 'DELETE' == newMethod.upper() or 'DEL' == newMethod.upper():
request.method = 'DELETE'
request.META['REQUEST_METHOD'] = 'DELETE'
request.DELETE = request.POST
( the code is from an open piston ticket here http://bitbucket.org/jespern/django-piston/issue/83/use-x-http-method-override-to-override-put )

- 1,523
- 1
- 12
- 20
You can find two answers here: http://groups.google.com/group/django-piston/browse_thread/thread/6f3f964b8b3ccf72/bd1658121bb1874c?show_docid=bd1658121bb1874c&pli=1
One way is to use request.FILES to get the filename, and then to save the image:
def create(self, request, nickname):
name = request.FILES["image"].name
image = PIL.Image.open(request.FILES["image"])
image.save(SOME_PATH+name)
return rc.ALL_OK
The second suggestion is to define an Image model and an ImageForm form, and use those:
def create(self, request, nickname):
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
Image.objects.create(image=form.cleaned_data['image'])
return rc.ALL_OK
return rc.BAD_REQUEST
WARNING: I haven't tested either of these methods!

- 1,101
- 7
- 8