2009年1月8日木曜日

Ajax file upload

byteflowのデコレータから引用していたけど、FileUploadに対応させました。

Ajaxでは
request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
が成り立つのですが、FileUploadはiframeを使いますのでつきません。
iframeでsubmitした場合、application/jsonにすると、ダウンロードが始まってしまうため、逃げます。

def ajax_request(func):
def wrapper(request, *args, **kw):
if request.method == 'POST':
response = func(request, *args, **kw)
else:
response = {'error': {'type': 403,
'message':'Accepts only POST request'}}
if isinstance(response, dict):
if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
class JsonResponse(HttpResponse):
def __init__(self, data):
super(JsonResponse, self).__init__(
content=simplejson.dumps(data),
mimetype='application/json')
return JsonResponse(response)
else:
# for file upload
class IframeResponse(HttpResponse):
def __init__(self, data):
super(IframeResponse, self).__init__(
content=''%simplejson.dumps(data))
return IframeResponse(response)
else:
return response
return wraps(func)(wrapper)


jquery.form.jsを使うと、具合が大変よろしいです。

$('#image_form').ajaxForm({
dataType: 'json',
beforeSubmit: function() {if (!$('#icon').val()) return false},
success: function(data) { render(data) },
resetForm: true
})

dataTypeは'json'で。
beforeSubmitの第1引数のformDataはnameで引けないので不便。
第2引数のjqFormで、jqForm[0].icon.valueでもOK。
もっといい指定方法は知りたい。
clearFormがなぜか効かなかったのでresetForm。

jquery.blockUI.jsで画像選択やアップロード画面を出すときれい。

jquery.js必須

0 件のコメント: