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

我尝试使用customHeaders,但没有成功。
虽然,$("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';
          }
    });
};


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

我在后端使用Django 1.9。我的前端表单如下所示:

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


Dgango标签{% csrf_token %}为页面标记生成<input type='hidden' name='csrfmiddlewaretoken' value='7CzH2kocMFDiGhSBlBY5OelS6oSND1Iw' />

最佳答案

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

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

如果这不起作用,则可以设置csrfmiddlewaretoken post参数内的令牌,而无需设置csrf标头,看起来您的插件支持使用data属性传递额外的参数。

关于javascript - 插入csrf token 以上传文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40193605/

10-08 23:33