3

如何在 Django 中上传文件并根据格式将它们保存(并在信号中采取其他操作 - post_save)在不同的位置?(JPEG和文档)

def upload(request):
    user = request.user
    upload_form = UploadForm(request.POST or None, request.FILES or None)
    if request.method == "POST":
        if upload_form.is_valid():
            my_model = upload_form.save(commit=False)
            my_model.user = user
            my_model.save()

楷模:

class FileStore(models.Model):
    user = models.ForeignKey(User)
    standard = models.FileField(upload_to="standard")
    after_operation = models.FileField(upload_to="after_ocr",blank=True, null=True)

信号:

@receiver(post_save, sender=FileStore)
def my_handler(sender,instance, **kwargs):
    if kwargs['created']:
        text= image_to_string(Image.open(instance.standard))
        ...
        instance.after_operation = File(text_file)
        instance.save()

我想如果文件是.doc.pdf只保存在standard字段中,如果文件是.jpeg.png我需要运行我的信号功能。

4

1 回答 1

4

例如,您可以通过访问request.FILES字典来检索上传的文件,如下所示:

uploaded_file = request.FILES['file']

uploaded_file现在是类型UploadedFile,这意味着您可以获得有关文件的信息,如下所示:

# name of the file, ie: my_file.txt
filename = uploaded_file.name
# file extension (get the las 4 chars)
file_ext = filename[-4:]
# handle file extension
if file_ext == '.jpg':
    # do something for jpegs
if file_ext == '.doc':
    # do something for docs

所以现在,为了保存它,你可以试试这个,我还没有证明:

# f is the UploadedFile
model_file = File(f)
model_file.save('path/to/wherever.ext', f.readlines(), true)

我希望这有帮助!这可能无法开箱即用,但我希望它能为问题带来一些启示。尝试查看文档:django 文件django 上传文件。这个主题有很好的记录。

祝你好运!

于 2013-05-30T13:40:03.970 回答