Thursday, November 21, 2013

Detect if uploaded file is saved to the temporary folder using Django

When uploading a file to the Django server, using HTML form and POST method, it is not always clear what is the used upload handler and if the file is saved to the temporary folder or just kept in the memory.

Here is one way to detect if the file is stored to the temporary folder or not.

def upload(request):
    uploaded_file = request.FILES['file']

    if isinstance(uploaded_file, TemporaryUploadedFile):
        # file has exceeded the value FILE_UPLOAD_MAX_MEMORY_SIZE

        # and it has been saved to the temporary folder
        print uploaded_tile.temporary_file_path()
        # closing the file will delete the file
        uploaded_file.close()
        return "file too large"
    else:
        # file is instance of InMemoryUploadedFile
    # handle file
    return "ok"

Other comparison function that can be used is:

    if hasattr(uploaded_file, 'temporary_file_path'):

Links: 
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
http://stackoverflow.com/questions/11835274/django-control-time-of-temporaryuploadedfile-life

No comments: