rahul.m
rahul.m

Reputation: 5854

Django save file without using form, just by using ajax

How can i save file in database without using forms.

models.py

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

ajax and 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')

Upvotes: 1

Views: 895

Answers (1)

heemayl
heemayl

Reputation: 42007

GET method can't transport any content data, so you need to use POST method:

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

Now, inside your view you can get the file-like object from 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, if you receive the data as POST param, you can use io.BytesIO to get a file-like object, and use it to create model record:

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, you should name your model classes as CamelCase.

The above is a basic idea of how to do this, you can enhance the idea to meet your need.

Upvotes: 3

Related Questions