I've been using something like this. I'm not sure if it's the best way
to do this ( everyone else - please correct me ), but the main idea id
that the file info will be in request.FILES.

# TEMPLATE:

<form action="{{myapp}}/upload/" method="post"
enctype="multipart/form-data" >
File: <input type="file" name="file" id="file">
<input type="submit" value="Upload File">
</form>



# VIEW:
def save_file( request ):

   import os.path

   # where to store files. Probably best defined in settings.py
   filepath = '/home/simon/files/'

   # right, so 'file' is the name of the file upload field
   filename = request.FILES[ 'file' ][ 'filename' ]
   filetype = request.FILES[ 'file' ][ 'content-type' ]

   #the uploaded data from the file
   data = request.FILES[ 'file' ][ 'content' ]

   # the full file path and name
   fullfilepath = os.path.join( filepath, filename )

   # clean up filenames & paths:
   fullfilepath = os.path.normpath( fullfilepath )
   fullfilepath = os.path.normcase( fullfilepath )

   # try to write file to the dir.
   try:
        f = open( fullfilepath, 'wb' ) # Writing in binary mode for windows..?

        f.write( data )
        f.close( )
   except:
        # something went wrong

--Simon

Reply via email to