Django仅使用ajax即可保存文件而无需使用表单

时间:2019-06-27 11:21:19

标签: python django ajax

如何不使用表单就将文件保存在数据库中。

models.py

class mymodel(models.Model):
     myfile = models.FileField(upload_to='folder/', blank=True, null=True)

ajax和html

<input id="id_video" type="file">
<button onclick="upload_video()">save</button>

function upload_video(){

    var formData = new FormData();
    formData.append('file', $('#id_video')[0].files[0]);

    console.log(formData)

    $.ajax({
        type:'GET', url : '/upload-video/',
        async: true,
        data:formData,,
        contentType: false,
        processData: false,
        success : function(data){
            alert(data)
        }
    })
}

views.py

def upload_videos(request):

    video_file = request.GET.get('formData')
    # how to save
    video_file.save()
    return Httpresponse('saved')

1 个答案:

答案 0 :(得分:2)

GET方法不能传输任何内容数据,因此您需要使用POST方法:

$.ajax({
    type: 'POST',
    ...
}

现在,在view中,您可以从request.FILES获取类似文件的对象:

def upload_videos(request):
    video_file = request.FILES['file']

    # Create model record
    _ = mymodel.objects.create(myfile=video_file.getvalue()) 

    return Httpresponse('saved')

OTOH,如果您收到data作为POST参数,则可以使用io.BytesIO获取类似文件的对象,并使用它来创建模型记录:

import io

def upload_videos(request):
    try:
        video_file = request.FILES['file']
    except KeyError:
        # You can catch KeyError here as well
        # and return a response with 400 status code
        try:
            video_file_data = request.POST['data']
        except KeyError:
            return Httpresponse('No file content', status=400)

        video_file = io.BytesIO(video_file_data)

        # Create model record
        _ = mymodel.objects.create(myfile=video_file.getvalue())
    else:             
        # Create model record
        _ = mymodel.objects.create(myfile=video_file.getvalue()) 

    return Httpresponse('saved')

FWIW,您应该将模型类命名为 CamelCase

以上是执行此操作的基本思想,您可以增强此思想以满足您的需求。