403 Forbidden error on swfupload and django

爷,独闯天下 提交于 2019-12-07 00:42:25

This is totally related with CSRF protection. In my case I solved that issue such that,

views.py

def photo_upload(request):
    if request.method == 'POST':
         for field_name in request.FILES:
         ....
         ....
         return HttpResponse("ok", mimetype="text/plain")

    else:       
         return render_response(request, 'wpphotos/post/photo_upload.html', {"csrf_token": get_token(request)},context_instance=RequestContext(request))

Because flash useses its own session while uploading, you should set csrf_token value in your middleware such that

swfupload.py

from django.conf import settings
from django.core.urlresolvers import reverse

class SWFUploadMiddleware(object):

def process_request(self, request):
    if (request.method == 'POST') and (request.path == reverse('project_name.module_name.views.photo_upload')) and \
            request.POST.has_key(settings.SESSION_COOKIE_NAME):
        request.COOKIES[settings.SESSION_COOKIE_NAME] = request.POST[settings.SESSION_COOKIE_NAME]
    if request.POST.has_key('csrftoken'):           
        request.COOKIES['csrftoken'] = request.POST['csrftoken']

For the last step, you should set csrftoken as post parameter in your javascript for SWFUpload settings such that

photo_upload.html

window.onload = function() {
    swfupload = new SWFUpload({
        post_params: {
            "csrfmiddlewaretoken": "{{csrf_token}}"
        },
        upload_url: "/module_name/post/photo_upload/",
        flash_url: "/media/flash/swfupload.swf",
        file_size_limit : "2.5 MB",
                    ....
                    ....
                    ....
            });
    };

I use uploadify in my django project, get 403 error too, because django has CSRF protection. so i change this function in my views.py solve this problem.

from django.views.decorators.csrf import csrf_exempt    
@csrf_exempt
def ajax_flash_upload(request):

This is probably related to the flash cookie bug: your client has an authentication cookie that the flash is not including in its request to the server. Since the request doesn't have the auth cookie, it gets rejected with a 403.

Just add an extra data when initializing Uploadify (make your changes on "swf" and "uploader" settings):

$('#file_upload').uploadify({
            'formData' : { 'csrfmiddlewaretoken' : '{{csrf_token}}' },
            'swf'       : '/static/js/uploadify.swf',
            'uploader'  : '{% url upload %}',
            // Put your other options here
        });

Thank you very much, brsbilgic. I've tried your solution, and it worked! By the way, the middleware snippet should be modified to:

if request.POST.has_key('csrfmiddlewaretoken'):           
    request.COOKIES['csrftoken'] = request.POST['csrfmiddlewaretoken']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!