Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 66 lines (49 sloc) 2.264 kb
877ad2b @mikeorr Reorganize static assets and forms sections.
mikeorr authored
1 File Uploads
2 %%%%%%%%%%%%
3
4 There are two parts necessary for handling file uploads. The first is to
5 make sure you have a form that's been setup correctly to accept files. This
6 means adding ``enctype`` attribute to your ``form`` element with the value of
7 ``multipart/form-data``. A very simple example would be a form that accepts
8 an mp3 file. Notice we've setup the form as previously explained and also
9 added an ``input`` element of the ``file`` type.
10
11 .. code-block:: html
12 :linenos:
13
14 <form action="/store_mp3_view" method="post" accept-charset="utf-8"
15 enctype="multipart/form-data">
16
17 <label for="mp3">Mp3</label>
18 <input id="mp3" name="mp3" type="file" value="" />
19
20 <input type="submit" value="submit" />
21 </form>
22
23 The second part is handling the file upload in your view callable (above,
24 assumed to answer on ``/store_mp3_view``). The uploaded file is added to the
25 request object as a ``cgi.FieldStorage`` object accessible through the
26 ``request.POST`` multidict. The two properties we're interested in are the
27 ``file`` and ``filename`` and we'll use those to write the file to disk.
28
29 .. code-block:: python
30 :linenos:
31
32 import os
33 from pyramid.response import Response
34
35 def store_mp3_view(request):
36 # ``filename`` contains the name of the file in string format.
37 #
38 # WARNING: this example does not deal with the fact that IE sends an
39 # absolute file *path* as the filename. This example is naive; it
40 # trusts user input.
41
42 filename = request.POST['mp3'].filename
43
44 # ``input_file`` contains the actual file data which needs to be
45 # stored somewhere.
46
47 input_file = request.POST['mp3'].file
48
49 # Using the filename like this without cleaning it is very
50 # insecure so please keep that in mind when writing your own
51 # file handling.
52 file_path = os.path.join('/tmp', filename)
53 output_file = open(file_path, 'wb')
54
55 # Finally write the data to the output file
56 input_file.seek(0)
57 while 1:
58 data = input_file.read(2<<16)
59 if not data:
60 break
61 output_file.write(data)
62 output_file.close()
63
64 return Response('OK')
65
Something went wrong with that request. Please try again.