How to upload files in Django and save them in a different location depending on the format? (jpeg and doc)

djangofile-upload

How to upload files in Django and save them (and take other actions in the signal – post_save) in a different location depending on the format? (jpeg and doc)

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()

models:

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)

signal:

@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()

I want if file is .doc or .pdf save only in standard field and if file is .jpeg or .png I need run my signal function.

Best Solution

For instance, you can retrieve the uploaded file by accessing the request.FILES dictionary like this:

uploaded_file = request.FILES['file']

uploaded_file is now of type UploadedFile which means you can get info about the file like this:

# 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

So now, for saving it you may try this, I haven't prove it yet:

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

I hope this helps! This may not work out of the box but I hope it bring some light to the problem. Try to look at the docs: django files and django uploaded files. This topic is very well documented.

Good luck!