通过Ajax将文件发送到Django

时间:2018-04-19 12:42:11

标签: ajax django file csrf

我正在处理数据只是POST或通过AJAX GET,直到文件想要引起一些问题:P

如果我将 processData contentType 设置为 true ,则AJAX dosnt可以正常工作。但是,如果我将 processData contentType 设置为 false ,则会出现CSRF TOKEN MISSING错误。

如何使用' csrfmiddlewaretoken'发送代码?并且能够管理文件。

这是我的jQuery代码:

$(document).ready(function(){
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$('.guardar-cambios-pedido').click(function(){
    var url = $(this).data('url');
    // Obtiene los datos de los inputs
    if ($("#editarPedidoModal .checkAnuladoPedido").is(":checked")){
        var anulado = true;
    } else {
        var anulado = false;
    }
    var codigo = $('.inputCodigoPedido').val();
    var usuario = $('.inputUsuarioPedido').val();
    var estado = $('.selectEstadoPedido').val();
    var factura = $('.inputFacturaPedido').prop('files')[0];

    // Crea un objeto datos
    datos = {
        'codigo': codigo,
        'usuario': usuario,
        'estado': estado,
        'factura': factura,
        'anulado': anulado,
    }
    // Envia los datos e los inputs al servidor
    $.ajax({
        type: 'POST',
        url: url,
        data: {'datos': datos},
        processData: false,
        //contentType: false,
        //dataType: "multipart/form-data",
        success: function(contenido){
                    //things done if success
        }
});

 . . . more code . . .

在我的views.py 中 我试图以这种方式接收我的数据:

if req.POST:
    normal_data = req.POST.get('datos[key]', '')
    file_data = req.FILES.get('datos[factura]', '')

更新1:我已经更新了我的代码,现在CSRF问题已经消失。我现在所拥有的是我无法从视图中访问数据。 AJAX调用返回成功,但即使尝试使用数据[&#39; key&#39;]或输入名称也没有数据。

我是否错过了&#34;发送数据的方式&#34;?

1 个答案:

答案 0 :(得分:0)

最后,我通过执行以下操作找到了解决方案:

添加了malsup jQuery表单插件:http://malsup.com/jquery/form/#getting-started

<script src="http://malsup.github.com/jquery.form.js"></script>    

在我的JS上,我已经设置了选项并通过ajaxSubmit()提交了表单

$("#btn-submit").click(function(){
    options = {
        url: $('#form').prop('action'),
        type: 'POST',
        success: function(response) {
            alert('Done');
            }
        };
    $('#form').ajaxSubmit(options)
})

在我的django视图中,我得到的数据与任何其他POST请求一样。

def some_view(request):
    if request.POST:
        other_inputs = request.POST.get('input_name', '')
        file_input = request.FILES.get('input_name', '')
        ... more code ...

标题上的CSRF TOKEN:

$(document).ready(function(){
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

}); // Ends document.ready

氰!