0

我是 Django 的新手。假设我有一个表单,我想用 ajax 向服务器提交一个文件。

我注意到当我没有在 post 语句中指定 csrf 令牌时服务器出现 HTTP 403 错误(正确的行为),但不知何故该文件仍然能够上传到服务器......

这是我的示例代码:

models.py(包括模型和形式):

from django.db import models
from django.forms import ModelForm

# Create your models here.
class Dummy(models.Model):
    myfile = models.FileField(upload_to='temp')

class DummyForm(ModelForm):
    class Meta:
        model = Dummy
        fields = ['myfile',]

视图.py:

# Create your views here.
class TestFormView(View):
def get(self, request):
    form = DummyForm()

    context = { 'form' : form }
    print form
    return render(request, 'testform.html', context)

def post(self, request):
    print request.FILES
    form = DummyForm(request.POST, request.FILES)
    print form.is_valid()
    print form.errors
    print form.is_bound
    if form.is_valid():
        form.save()

    print Dummy.objects.all().count()
    return render(request, 'testform.html')

testform.html:

<form id="myForm" action="testform/" method="post" enctype="multipart/form-data">
{% csrf_token %}
 <input id="id_myfile" type="file" size="60" name="myfile">
 <input type="submit" value="Ajax File Upload">
</form>

<div id="progress">
    <div id="bar"></div>
    <div id="percent">0%</div >
</div>
<br/>

<div id="message"></div>

<script>
$(document).ready(function()
{

var options = {
beforeSend: function()
{
    $("#progress").show();
    //clear everything
    $("#bar").width('0%');
    $("#message").html("");
    $("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
    $("#bar").width(percentComplete+'%');
    $("#percent").html(percentComplete+'%');

},
success: function()
{
    $("#bar").width('100%');
    $("#percent").html('100%');

    alert("done!");

},
complete: function(response)
{
    $("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
    $("#message").html("<font color='red'> ERROR: unable to upload files</font>");

}

};

 $("#myForm").ajaxForm(options);

 $("#myForm").submit(function(event) {
    event.preventDefault();

    var $form = $(this);
    var url = $form.attr('action');

    $.post("testform/", { myfile: $('#myfile').val()});

    return false;

 });

});

</script>

当然,如果我将 csrf 令牌放在 $post 函数中,我会得到 HTTP 200。

我担心这是否会造成安全漏洞,因为看起来任何人都可以将文件上传到服务器?

谢谢!

4

0 回答 0