Sol
Sol

Reputation: 790

How to locally save a pdf file from file object?

I am trying to upload a pdf file and just save it locally received from a FILE request.

If it helps the file type returns the following: class 'django.core.files.uploadedfile.InMemoryUploadedFile'

def file_upload(request):
    lesson_file = request.FILES['file']
    # Save file to same directory
    lesson_file.save('file_name.pdf') #This is just an example of what I want to achieve

Upvotes: 1

Views: 1899

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

Simple upload function:

def upload_func(file):
    with open('your/custom/path/filename.fileformat', 'wb+') as f:
        for chunk in file.chunks():
            f.write(chunk)

Upload with a model:

model:

class MyFileModel:
    file = models.FileField()
    # ...

upload:

my_obj = MyFileModel.objects.create(file=request.FILES['file'])

You can use upload_to to change the path:

FileField.upload_to

Upvotes: 3

Related Questions