Django,带有额外数据的ajax上传文件

时间:2017-11-07 01:43:06

标签: python ajax django

我有一个小问题,我想上传一个带有一些额外数据的文件。

所以我现在正在做的是:

JS文件:

$(document).on('submit', '.upload-file', function(e){
    e.preventDefault();

    var form_data = new FormData($(this)); //I dont know why, but it used to return None
        //so I append file and some extra data
        form_data.append( 'file', ($(this).find('[type=file]')[0].files[0]) );
        form_data.append( 'expire', ($(this).find('.document-id').val()) );
        form_data.append( 'document', ($(this).find('[type=datetime-local]').val()) );

    $.ajax({
        type : 'POST',
        url : 'some_url',
        data : form_data,
        cache: false,
        processData: false,
        contentType: false,
    }).done(function(data) {
        console.log(data);      
    });

});

Views.py

def upload_file(request):
    if request.method =='POST':
        data = request.POST.get('data')
        file = request.FILES

        print('File ->', file) #this one prints File
        print('Data ->', data) #this one prints None

        return HttpResponse()

印刷数据:

 File -> <MultiValueDict: {'file': [<InMemoryUploadedFile: MyFile.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>]}>
 Data -> None

所以,我需要将文件发送到外部服务器,这需要一些额外的信息,但我不知道如何组合这些数据。

1 个答案:

答案 0 :(得分:0)

我猜你需要设置你的请求的内容类型。在您的AJAX调用中,您正在传递contentType: false。也许尝试将其更改为contentType: 'multipart/form-data'