File Uploads

There are two parts necessary for handling file uploads. The first is to make sure you have a form that's been setup correctly to accept files. This means adding enctype attribute to your form element with the value of multipart/form-data. A very simple example would be a form that accepts an mp3 file. Notice we've setup the form as previously explained and also added an input element of the file type.

1<form action="/store_mp3_view" method="post" accept-charset="utf-8"
2      enctype="multipart/form-data">
3
4    <label for="mp3">Mp3</label>
5    <input id="mp3" name="mp3" type="file" value="" />
6
7    <input type="submit" value="submit" />
8</form>

The second part is handling the file upload in your view callable (above, assumed to answer on /store_mp3_view). The uploaded file is added to the request object as a cgi.FieldStorage object accessible through the request.POST multidict. The two properties we're interested in are the file and filename and we'll use those to write the file to disk:

 1import os
 2import uuid
 3import shutil
 4from pyramid.response import Response
 5
 6def store_mp3_view(request):
 7    # ``filename`` contains the name of the file in string format.
 8    #
 9    # WARNING: this example does not deal with the fact that IE sends an
10    # absolute file *path* as the filename.  This example is naive; it
11    # trusts user input.
12
13    filename = request.POST['mp3'].filename
14
15    # ``input_file`` contains the actual file data which needs to be
16    # stored somewhere.
17
18    input_file = request.POST['mp3'].file
19
20    # Note that we are generating our own filename instead of trusting
21    # the incoming filename since that might result in insecure paths.
22    # Please note that in a real application you would not use /tmp,
23    # and if you write to an untrusted location you will need to do
24    # some extra work to prevent symlink attacks.
25
26    file_path = os.path.join('/tmp', '%s.mp3' % uuid.uuid4())
27
28    # We first write to a temporary file to prevent incomplete files from
29    # being used.
30
31    temp_file_path = file_path + '~'
32
33    # Finally write the data to a temporary file
34    input_file.seek(0)
35    with open(temp_file_path, 'wb') as output_file:
36        shutil.copyfileobj(input_file, output_file)
37
38    # Now that we know the file has been fully saved to disk move it into place.
39
40    os.rename(temp_file_path, file_path)
41
42    return Response('OK')