CSRF验证失败

时间:2013-12-20 13:48:42

标签: javascript python django xmlhttprequest

我在Django应用程序中使用XMLHttpRequest()发送图像文件。这是我的剧本:

$('#edit_user_image').change(function(){
    var client = new XMLHttpRequest();
    var file = document.getElementById("edit_user_image");
    /* Create a FormData instance */
    var formData = new FormData();
    /* Add the file */ 
    formData.append("csrfmiddlewaretoken", document.getElementsByName('csrfmiddlewaretoken')[0].value);
    formData.append("upload", file.files[0]);


    client.open("post", "/upload-image/", true);
    client.setRequestHeader("Content-Type", "multipart/form-data; charset=utf-8; boundary=frontier");
    client.send(formData);  /* Send to server */ 
  });

这是我的html输入:

Upload New Photo
{% csrf_token %}
<input id="edit_user_image" name="image" type="file" />

但是,当生成XMLHttpRequest()时,即使我将其附加到数据中,也会出现“CSRF验证失败”错误。任何人都可以告诉脚本有什么问题。

1 个答案:

答案 0 :(得分:2)

以下是我所做的一些更改,现在工作正常:

$('#edit_user_image').change(function(){
    var client = new XMLHttpRequest();
    var file = document.getElementById("edit_user_image");
    var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
    /* Create a FormData instance */

    var params = file.files[0];


    client.open("post", "/upload-image/", true);
    client.setRequestHeader("X-CSRFToken", csrftoken);
    client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier");
    client.send(params);  /* Send to server */ 
  });