[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Uploading Client Files to the Server


The getfile script lets us view server files on the client, but in some sense, it is a general-
purpose file download tool. Although not as direct as fetching a file by FTP or over raw
sockets, it serves similar purposes. Users of the script can either cut-and-paste the dis-
played code right off the web page or use their browser’s View Source option to view
and cut. As described earlier, scripts that contact the script with urllib can also extract
the file’s text with Python’s HTML parser module.


But what about going the other way—uploading a file from the client machine to the
server? For instance, suppose you are writing a web-based email system, and you need
a way to allow users to upload mail attachments. This is not an entirely hypothetical
scenario; we will actually implement this idea in the next chapter, when we develop
the PyMailCGI webmail site.


As we saw in Chapter 13, uploads are easy enough to accomplish with a client-side
script that uses Python’s FTP support module. Yet such a solution doesn’t really apply
in the context of a web browser; we can’t usually ask all of our program’s clients to
start up a Python FTP script in another window to accomplish an upload. Moreover,
there is no simple way for the server-side script to request the upload explicitly, unless
an FTP server happens to be running on the client machine (not at all the usual case).
Users can email files separately, but this can be inconvenient, especially for email
attachments.


So is there no way to write a web-based program that lets its users upload files to a
common server? In fact, there is, though it has more to do with HTML than with Python
itself. HTML tags also support a type=file option, which produces an input
field, along with a button that pops up a file-selection dialog. The name of the client-
side file to be uploaded can either be typed into the control or selected with the pop-
up dialog. To demonstrate, the HTML file in Example 15-29 defines a page that allows
any client-side file to be selected and uploaded to the server-side script named in the
form’s action option.


Example 15-29. PP4E\Internet\Web\putfile.html


Putfile: upload page

method=post
action="cgi-bin/putfile.py">

Select client file to be uploaded






View script code

One constraint worth noting: forms that use file type inputs should also specify a
multipart/form-data encoding type and the post submission method, as shown in this


1218 | Chapter 15: Server-Side Scripting

Free download pdf