Samstag, 16. Januar 2010

File uploads using with ajax using jquery.form and TurboGears 2.1

While trying to follow the ajax file upload example from http://jquery.malsup.com/form/#file-upload I was running into trouble with the server response. I was expecting the server to return json, which I wanted to parse in a callback function. What happened was that the server did its job perfectly and returned content-type application/json. However, the browser (in this case Firefox 3.5) prompted me to download the response, rather than to parse it in the callback function. This is obviously useless.

The answer was to return content-type text/plain instead of application/json. To do this in TurboGears 2.1, I followed an example from Pylons. My controller now looks like this:
   @expose()
    def uploadFile(self,**kwargs):
        """ Simple controller to handle uploaded files
        """
        # do stuff such as handle file upload...
        response.headers['Content-type'] = "text/plain"
        return dict(info={'filesize':50000,'filename':'whatever')
Note the response.headers['Content-type'] = "text/plain" - and that I left out the expose('json') which you would normally use in TurboGears to return json...

Keine Kommentare: