Hi,

I see what may be a gap in the new upload system's API. Please correct
me or point me to the right place if I'm wrong.

Once the file is uploaded and my view receives the UploadedFile
instance, I'd like to write the file on disk to my chosen path. The
API already provides a proxy for the common file operations, which is
great, but I wonder how I could actually do the writing/copying to the
right path without clogging up the memory.

The current way I see is that you need to use the read method, which
will load the whole file in memory unless you provide a length. So,
typically, you'd need to loop into the file to make the copy,
something along the lines of:

while there's something to read:
    chunk = uploaded_file.read(settings.FILE_UPLOAD_MAX_MEMORY_SIZE)
    output_file.write(chunk)

To achieve what I want to do (and which I believe is a common
operation) I've written a helper function:

from shutil import copyfileobj

def writeToPath(uploaded_file, path):
    output = open(path, "wb")
    if isinstance(uploaded_file, InMemoryUploadedFile):
        # Directly write from memory to the new file
        output.write(uploaded_file.file)
        output.close()
    elif isinstance(uploaded_file, TemporaryUploadedFile):
        # Write chunk by chunk from the temp file to the new file
        copyfileobj(uploaded_file._file.file, output,
settings.FILE_UPLOAD_MAX_MEMORY_SIZE)
        output.close()

So, my bottom line question is: should there be a similar helper
function provided in the UploadedFile API, or should that be left
entirely to the developer?

Thanks,

Julien
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to