用ajax和django发送图像

时间:2019-04-15 19:11:56

标签: python jquery ajax django

我尝试从<input type="file" id="file" name="file" accept="image/*" multiple>发送图像而不发送任何表格。我发现很多帖子对此做了解释,所以我这样做

urls.py

url(r'^images/', 'app.views.images', name='images'),

view.py

def images(request):
    if request.method == 'POST':
        print('hello')

jquery

$("#file").change(function (){
    try{
        var formdata = new FormData();
        var files = $('#file')[0].files;
        formdata.append('file',files);
        jQuery.ajax({
                    url: "images/",
                    type: "POST",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    success: function (result) {
                         // if all is well
                         // play the audio file
                    }
                });
        }
    catch(err){
        alert(err.message);
        }
});

但这给了我"POST /images/ HTTP/1.1" 403错误

我做了不同的测试,我认为错误是data: formdata部分

1 个答案:

答案 0 :(得分:1)

您需要在ajax请求中发送csrf_token

formdata["csrfmiddlewaretoken"] = '{{ csrf_token }}';  //add csrf token to the reauest data
jQuery.ajax({
    url: "images/",
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    success: function (result) {
        // if all is well
        // play the audio file
    }
});

或在您的视图上使用@csrf_exempt

#views.py

@csrf_exempt
def images(request):
    if request.method == 'POST':
        print('hello')