在上传模块的帮助下,不要在nginx上传文件

时间:2013-01-17 05:10:26

标签: django upload module nginx

在我的项目中出现了问题。不上传文件。这是我的代码

配置nginx

server{

listen 9000;
server_name localhost;
root  /home/path/my/project;

location ~ ^/(static|media)/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
}

location /file-upload {
    internal;
    upload_pass /upload-file/;
    upload_store /home/payh/my/project/media/video;
    upload_max_file_size 250m;

    upload_set_form_field $upload_field_name.name "$upload_file_name";
    upload_set_form_field $upload_field_name.content_type "$upload_content_type";
    upload_set_form_field $upload_field_name.path "$upload_tmp_path";

    upload_pass_form_field "^csrfmiddlewaretoken$";

    upload_limit_rate 2m;
    track_uploads upload 1m;
}

location = /upload/progress {
    report_uploads upload;
}

location / {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_connect_timeout 10;
    proxy_read_timeout 10;
    proxy_pass http://localhost:8000/;
}
error_page 500 502 503 504 /media/50x.html;
}

点击按钮上传后,请求由nginx_accel执行。然后查看nginx的创建响应并发送它。 Nginx不允许返回405。我不是为什么。 我的views.py

@login_required
@csrf_protect
def upload(request):
    context = RequestContext(request)

    if request.method == 'POST':
        pathfile = request.POST.get('upfile.path')
        upfile   = open(pathfile, 'r')
        file = File(upfile)

        form = NewFileForm(request.POST, initial={'upfile':file})
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(upload))
    else:
        form = NewFileForm()

    return render_to_response('upload.html', 
                          {'form':form},
                           context_instance=context)    
@login_required
@csrf_protect
def nginx_accel(request):
    if request.user.id == 1:
        file = request.FILES.get('upfile').name
        url = '/'.join(['/file-upload', file])
        response = HttpResponse()

        response['Content-Type']= ''
        response['X-Accel-Redirect'] = url

        return response

浏览器中的Nginx返回“405不允许”。有人能说出现这个问题的原因吗?

2 个答案:

答案 0 :(得分:0)

错误的原因是file = request.FILES.get('upfile').name。它将绕过并尝试在POST请求上提供静态文件,从而导致405错误。解决问题。

@login_required
@csrf_protect
def nginx_accel(request):
    if request.method == 'GET':
        if request.user.id == 1:
            file = request.GET.get('upfile').name
            url = '/'.join(['/file-upload', file])
            response = HttpResponse()

            response['Content-Type']= ''
            response['X-Accel-Redirect'] = url

            return response

答案 1 :(得分:0)

尝试:删除字符串内部;
在位置/文件上传
如果请求的方法不是POST,则模块返回错误405(不允许方法)。可以通过error_page指令在备用位置处理具有此类方法的请求。 more info