插入csrf令牌以进行文件上载

时间:2016-10-22 15:05:06

标签: javascript django

如何在LPology/Simple-Ajax-Uploader中插入csrf令牌?

我尝试$("input[name='csrfmiddlewaretoken']").val()但没有成功。 虽然qEN1kNfYYkAasfqBn3AigICJmz4MIlei给出了var uploader = new ss.SimpleUpload({ button: btn, url: 'file_upload/', name: 'uploadfile', customHeaders: { 'X-CSRF-TOKEN': $("input[name='csrfmiddlewaretoken']").val() }, multipart: true, hoverClass: 'hover', focusClass: 'focus', responseType: 'json', startXHR: function() { progressOuter.style.display = 'block'; // make progress bar visible this.setProgressBar( progressBar ); }, onSubmit: function() { msgBox.innerHTML = ''; // empty the message box btn.innerHTML = 'Uploading...'; // change button text to "Uploading..." }, onComplete: function( filename, response ) { btn.innerHTML = 'Choose Another File'; progressOuter.style.display = 'none'; // hide progress bar when upload is completed if ( !response ) { msgBox.innerHTML = 'Unable to upload file'; return; } if ( response.success === true ) { msgBox.innerHTML = '<strong>' + escapeTags( filename ) + '</strong>' + ' successfully uploaded.'; } else { if ( response.msg ) { msgBox.innerHTML = escapeTags( response.msg ); } else { msgBox.innerHTML = 'An error occurred and the upload failed.'; } } }, onError: function() { progressOuter.style.display = 'none'; msgBox.innerHTML = 'Unable to upload file'; } }); };

<form>{% csrf_token %}
...
</form>

完整示例:https://github.com/LPology/Simple-Ajax-Uploader/tree/master/examples/basic_example

我在后端使用Django 1.9。我的前端形式如下:

{% csrf_token %}

Dgango代码<input type='hidden' name='csrfmiddlewaretoken' value='7CzH2kocMFDiGhSBlBY5OelS6oSND1Iw' />为页面标记生成$text = str_replace('�', '"', $text);

1 个答案:

答案 0 :(得分:2)

标题应该被称为X-CSRFToken而不是X-CSRF-TOKEN

如果这不起作用,请尝试从csrftoken cookie而不是隐藏输入中检索令牌值。

如果这不起作用,可以在csrfmiddlewaretoken post param中提交令牌,而不是设置csrf头,看起来你的插件支持使用data属性传递额外的参数。