如何从文件对象本地保存pdf文件?

时间:2019-05-04 16:26:01

标签: python django pdf

我正在尝试上传pdf文件,并将其保存在本地从FILE请求中接收到的文件中。

如果有帮助,文件类型将返回以下内容:类'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

1 个答案:

答案 0 :(得分:1)

简单的上传功能:

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

上传模型:

型号:

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

上传:

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

您可以使用upload_to来更改路径:

FileField.upload_to