Uploading Files

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 shutil
 3
 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: Internet Explorer is known to send an absolute file
10    # *path* as the filename.  This example is naive; it trusts
11    # user input.
12    filename = request.POST['mp3'].filename
13
14    # ``input_file`` contains the actual file data which needs to be
15    # stored somewhere.
16    input_file = request.POST['mp3'].file
17
18    # Using the filename like this without cleaning it is very
19    # insecure so please keep that in mind when writing your own
20    # file handling.
21    file_path = os.path.join('/tmp', filename)
22    with open(file_path, 'wb') as output_file:
23        shutil.copyfileobj(input_file, output_file)
24
25    return Response('OK')